Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 536
user6465508 Avatar asked Feb 07 '23 17:02

user6465508


1 Answers

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
like image 195
sepp2k Avatar answered Feb 19 '23 14:02

sepp2k