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?
The arrow ->
is a short syntax to create lambas. See " What do you call the -> operator in Ruby? ".
An alternative way could be the following snippet:
results.map { |object| object["name"] }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.