How do I list all objects created from a class in Ruby?
You can use the ObjectSpace
module to do this, specifically the each_object
method.
ObjectSpace.each_object(Project).count
For completeness, here's how you would use that in your class (hat tip to sawa)
class Project
# ...
def self.all
ObjectSpace.each_object(self).to_a
end
def self.count
all.count
end
end
Ruby. How to collect all class elements from all class objects?
You need to make name_list
a class variable
class Animal
attr_accessor :name
@@name_list = []
def initialize
@name = name
end
def set_name
@name = gets
puts "My name is #{@name}"
@@name_list.push(@name.strip)
end
def self.show_all
puts "List of your animals names: #{@@name_list}"
end
end
How to find each instance of a class in Ruby
The solution is to use ObjectSpace.each_object
method like
ObjectSpace.each_object(Pokemon) {|x| p x}
which produces
<Pokemon:0x0000010098aa70>
<Pokemon:0x00000100992158>
=> 2
Details are discussed in the PickAxe book Chapter 25
return attributes from all objects of a class in ruby
The problem you have right now is that Player
is your custom class. It does not respond to a class method each
. Another issue is that the Player
class has no knowledge of the instances created outside of it.
There's many ways to go about this. The way I would do this is to implement another class called Team like this
class Team
def initialize(*players)
@players = players
end
def player_numbers
@players.map { |player| player.number }
end
end
class Player
attr_reader :number
def initialize(name, number)
@name = name
@number = number
end
end
guy1 = Player.new('Bill', 23)
guy2 = Player.new('jeff', 18)
team = Team.new(guy1, guy2)
team.player_numbers
#=> [23, 18]
Extract objects by their properties from list of class names in ruby
This sets @fruits
with the list of Fruit
Objects matching color: 'red'
and @vegetables
the list of Vegetable
Objects matching color: 'red'
obj_list = ["Fruit", "Vegetable"]
obj_list.each do |c|
list_name = "@#{c.downcase}s"
list_objects = Object.const_get(c).where(color: 'red')
instance_variable_set(list_name, list_objects)
end
@fruits #=> Fruit.where(color: 'red')
@vegetables #=> Vegetable.where(color: 'red')
hope this helps
Look up all descendants of a class in Ruby
Here is an example:
class Parent
def self.descendants
ObjectSpace.each_object(Class).select { |klass| klass < self }
end
end
class Child < Parent
end
class GrandChild < Child
end
puts Parent.descendants
puts Child.descendants
puts Parent.descendants gives you:
GrandChild
Child
puts Child.descendants gives you:
GrandChild
How to list all methods for an object in Ruby?
The following will list the methods that the User class has that the base Object class does not have...
>> User.methods - Object.methods
=> ["field_types", "maximum", "create!", "active_connections", "to_dropdown",
"content_columns", "su_pw?", "default_timezone", "encode_quoted_value",
"reloadable?", "update", "reset_sequence_name", "default_timezone=",
"validate_find_options", "find_on_conditions_without_deprecation",
"validates_size_of", "execute_simple_calculation", "attr_protected",
"reflections", "table_name_prefix", ...
Note that methods
is a method for Classes and for Class instances.
Here's the methods that my User class has that are not in the ActiveRecord base class:
>> User.methods - ActiveRecord::Base.methods
=> ["field_types", "su_pw?", "set_login_attr", "create_user_and_conf_user",
"original_table_name", "field_type", "authenticate", "set_default_order",
"id_name?", "id_name_column", "original_locking_column", "default_order",
"subclass_associations", ...
# I ran the statements in the console.
Note that the methods created as a result of the (many) has_many relationships defined in the User class are not in the results of the methods
call.
Added Note that :has_many does not add methods directly. Instead, the ActiveRecord machinery uses the Ruby method_missing
and responds_to
techniques to handle method calls on the fly. As a result, the methods are not listed in the methods
method result.
How to list all the methods defined in top self Object in Ruby?
The closest I could find is to call private_methods
on the main
object, with false
as argument
Returns the list of private methods accessible to obj. If the all
parameter is set to false, only those methods in the receiver will be
listed.
def foo
"foo"
end
def bar
"bar"
end
def baz
"baz"
end
p private_methods(false)
# [:include, :using, :public, :private, :define_method, :DelegateClass, :foo, :bar, :baz]
If you omit the argument, you also get all the private methods defined in Kernel
or BasicObject
.
In order to refine the list further, you could select the methods defined for Object
:
p private_methods(false).select{|m| method(m).owner == Object}
#=> [:DelegateClass, :foo, :bar, :baz]
Only :DelegateClass
is left, because it is defined in the top-level scope, just like :foo
, :bar
and :baz
.
Get list of a class' instance methods
You actually want TestClass.instance_methods
, unless you're interested in what TestClass
itself can do.
class TestClass
def method1
end
def method2
end
def method3
end
end
TestClass.methods.grep(/method1/) # => []
TestClass.instance_methods.grep(/method1/) # => ["method1"]
TestClass.methods.grep(/new/) # => ["new"]
Or you can call methods
(not instance_methods
) on the object:
test_object = TestClass.new
test_object.methods.grep(/method1/) # => ["method1"]
Related Topics
Getting Only New Mail from an Imap Server
When to Use a Lambda in Ruby on Rails
Finding the Session Id in Rails 3
How to Access (Devise) Current_User in a Rspec Feature Test
Sidekiq Not Deallocating Memory After Workers Have Finished
Stack Level Too Deep Error in Ruby on Rails
Getting Viewable Text Words via Nokogiri
How to Determine the Md5 Digest of a Given Asset in the Rails Asset Pipeline
Ruby on Rails: Devise, Want to Add Invite Code
Change the Context/Binding Inside a Block in Ruby
Passing Headers and Query Params in Httparty
Rails Link_To External Site, Url Is Attribute of User Table, Like: @Users.Website