-2

I was working on a coding problem at codewars.com. This is the answer to said problem:

class Conjurer
  def self.conjure(name, lambda)
    define_method name, lambda
  end
end

I would like to articulate the way I am reading it, and receive criticism that helps me better understand the meaning of this code.

  1. The class Conjurer is created.
  2. An instance method of the class is called, representing the class itself.
  3. It is given permanent parameters name and lambda.
  4. Unsure what define_method name, lambda means.
sawa
  • 165,429
  • 45
  • 277
  • 381
Erik Aasland
  • 167
  • 1
  • 11

2 Answers2

2

define_method makes a method named name and passes it a block lambda. So if you call the method name, it runs the block represented by the variable lamba.

The self.conjure is allowing you do define a method within the class: the name parameter becomes the name of the method, the lambda becomes the body of the method itself.

Charles
  • 1,384
  • 11
  • 18
2
  1. The class Conjurer is created.

Yes. More accurately, the Conjurer class is opened, meaning that it's being opened for modification. In this case, the conjure method is being added.

In Ruby, you can open a class many times:

class Conjurer
  def self.something
    # code
  end
end

class Conjurer
  def self.other_thing
    # code
  end
end

This is the same as doing

class Conjurer
  def self.something
    # code
  end

  def self.other_thing
    # code
  end
end
  1. An instance method of the class is called, representing the class itself.

No. It's not a method call, it's a method definition. The def keyword defines a new method. The def self. defines a method for the Conjurer class rather than a Conjurer.new instance.

  1. It is given permanent parameters name and lambda.

Almost. The parameters are name and lambda, but they're not arguments of a call (see here for the difference between argument and parameter), because that isn't a method call, is a method definition.

  1. Unsure what define_method name, lambda means.

define_method is part of the Ruby language. It does what is says, it defines a method with the name name that when called, executes lambda. See the docs here.

Community
  • 1
  • 1
tonchis
  • 598
  • 3
  • 10