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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With