user6465508
user6465508

Reputation: 57

What does the method `method` do in `&Unit.method(:new)`?

I'm new to the Rails and trying to figure out the code that im given. What does the method method do in &Unit.method(:new) ? And what is the meaning of &? There's not method method in Unit model and wondering why it can be there. And lastly, I guess the symbol :new creates a new object of Unit ?

class Unit
  include ActiveModel::Model

  attr_accessor :number 
end


class Product
  include ActiveModel::Model
  .........
  .........
  def units=(values)
    @units = values.map(&Unit.method(:new))
  end
end

Upvotes: 4

Views: 113

Answers (1)

sepp2k
sepp2k

Reputation: 370112

The method method is defined in the class Object and thus available on all objects. It takes as its argument the name of a method and returns a Method object that can be used to reflect on or call the given method.

So Unit.method(:new) gives you a Method object that represents the method Unit.new.

Now the unary & operator takes a Proc object or something that can be converted to a Proc using to_proc (which Method objects can) and then converts it to block.

So &Unit.method(:new) creates a block that calls the Unit.new method, making values.map(&Unit.method(:new)) equivalent to:

values.map do |value|
  Unit.new(value)
end

Upvotes: 8

Related Questions