-1

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?

5
  • 2
    @sschmeck's answer is good, but it's worth noting that this isn't great code. This code initializes a new lambda every time extract_name is 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). Commented Feb 5, 2016 at 22:40
  • 1
    @Jordan: Are you sure about that? I'm pretty sure that e.map(&m) will be parsed as e.map(&(m())) so m will only be called once and then & will be applied to its return value only once. Commented Feb 5, 2016 at 22:47
  • 1
    Yes, you're correct, but what I wrote is "This code initializes a new lambda every time extract_name is called." It won't be called for every iteration, but it will be called every time results.map(&extract_name) is called. Commented Feb 5, 2016 at 22:49
  • @Jordan So if I were to write two test's each one running the 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? Commented Feb 6, 2016 at 2:00
  • @Jordan Awesome! Thank you! Commented Feb 6, 2016 at 5:40

1 Answer 1

2

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"] }
Sign up to request clarification or add additional context in comments.

1 Comment

object[:name] should be object["name"] for equivalence with OP's code.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.