w3d5 Flashcards

1
Q

What is “reflection” in Ruby?

A

The ability for a program to examine itself.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How can we use #send to call a method?

A

Use the method name as a symbol argument:

[].send(:count)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How can we dynamically define methods?

A

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}!" }
  end

makes_sound(:woof)
makes_sound(:bark)
makes_sound(:grr)
end

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Are methods defined with ::define_method instance specific?

A

No

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Explain dynamic finders and how they work.

A

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
end

earl = Cat.new

earl. say_hello # puts “hello”
earl. say_goodbye # puts “goodbye”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How can you structure a method to receive multiple types of arguments?

A

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
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What are we doing, in essence, when we initialize an instance of an object?

A

We are adding an instance variable of the new object to the instance of the class.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How do we access all instances of a class?

A

ClassName.all

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How do we assign class variables, and why bother?

A

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 = name
self.class.all << self   end end
class Husky < Dog
end

h = Husky.new(“Rex”)

Dog.all # => #

How well did you know this?
1
Not at all
2
3
4
5
Perfectly