0

I have a field in animal_food (a json object) called treats and I want to add a field in treats called time_eaten and then return everything from the field treats.

 def addTime(time)
    animal_food["treats"]["time_eaten"] = time
    animal_food["treats"]
  end

Is there a way I can do the code above in 1 line (using merge or other ruby syntax?)

1 Answer 1

2

Yes:

animal_food['treats'].merge!({'time_eaten' => time})

does the same thing as those two lines. (Note the exclamation mark.) You could also say

animal_food['treats'].tap { |treats| treats['time_eaten'] = time }

Or, in Ruby 2.7 preview, using numbered parameters:

animal_food['treats'].tap { @1['time_eaten'] = time }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.