What is “reflection” in Ruby?
The ability for a program to examine itself.
How can we use #send to call a method?
Use the method name as a symbol argument:
[].send(:count)
How can we dynamically define methods?
With ::define_method:
class Dog # defines a class method that will define more methods; this is # called a **macro**.
def self.makes_sound(name)
define_method(name) { puts "#{name}!" }
endmakes_sound(:woof)
makes_sound(:bark)
makes_sound(:grr)
end
Are methods defined with ::define_method instance specific?
No
Explain dynamic finders and how they work.
By overriding #method_missing, you can define an infinite number of methods:
class Cat
def say(anything)
puts anything
end
def method_missing(method_name)
method_name = method_name.to_s
if method_name.start_with?("say_")
text = method_name[("say_".length)..-1] say(text)
else
# do the usual thing when a method is missing (i.e., raise an
# error)
super
end
end
endearl = Cat.new
earl. say_hello # puts “hello”
earl. say_goodbye # puts “goodbye”
How can you structure a method to receive multiple types of arguments?
Use logic in the method to decide what to do based on the given arguments:
def perform_get(url)
if url.is_a?(Hash)
# url is actually a hash of url options, call another method
# to turn it into a string representation.
url = make_url(url)
end
# ... end
What are we doing, in essence, when we initialize an instance of an object?
We are adding an instance variable of the new object to the instance of the class.
How do we access all instances of a class?
ClassName.all
How do we assign class variables, and why bother?
Use @@; this will allow inherited classes to be counted as instances of other classes:
class Dog
def self.all
@@dogs ||= []
end def initialize(name)
@name = nameself.class.all << self end end
class Husky < Dog end
h = Husky.new(“Rex”)
Dog.all # => #