I came across a way in which a program extracted the name property of an object and found the syntax a little peculiar. This is dealing with the results of JSON response.
Our JSON response would be the following =
[{"id"=>9, "name"=>"Baked Potato w/ Cheese", "instructions"=>nil},
{"id"=>12, "name"=>"Baked Brussel Sprouts", "instructions"=>nil}]
results = JSON.parse(response.body)
def extract_name
->(object) { object["name"] }
end
results.map(&extract_name)
So I understand that results.map(&extract_name) returns the name of the JSON objects, I just don't understand how.
I'm unfamiliar with the ->(object) { object["name"] } syntax. Are there are other shorthand ways of doing this that may help me get a better idea of this type of syntax?
extract_nameis called. It would be better to assign the lambda to a variable or constant, e.g.EXTRACT_NAME = ->(object) { object["name"] }; results.map(&EXTRACT_NAME).e.map(&m)will be parsed ase.map(&(m()))somwill only be called once and then&will be applied to its return value only once.extract_nameis called." It won't be called for every iteration, but it will be called every timeresults.map(&extract_name)is called.results.map(&extract_name), I will be initializing two lambdas as opposed to just setting it to a constant where it is only initialized once? To my understanding, this is more efficient yes?