0

In a .rb file I am using result = JSON.parse(res.body)['data']['results'] and get

[
  {"suggestion":"Lineman","id":"49.10526"},
  {"suggestion":"Linguist","id":"27.10195"},
  {"suggestion":"Librarian","id":"25.47"},
  {"suggestion":"Lifeguard","id":"33.39"},
  {"suggestion":"Line Cook","id":"35.30125"},
  {"suggestion":"Life Coach","id":"21.209"},
  {"suggestion":"Life Guard","id":"33.1001"}
]

now I want an array like

[
  "Lineman",
  "Linguist",
  "Librarian",
  "Lifeguard",
  "Line Cook",
  "Life Coach",
  "Life Guard"
]

What should I apply to JSON.parse(res.body)['data']['results']?

2
  • result is merely an array. That it came from a JSON string is irrelevant to your question. Commented May 17, 2021 at 18:45
  • It is unlikely that the top code block is what you receive from JSON parse since JSON parsing is always converted to String keys and what you have shown will result in Symbol keys. Yes, this distinction is important Commented May 17, 2021 at 19:16

2 Answers 2

1

You can use Enumerable#map:

  other_result = result.map { |val| val['suggestion'] }

it returns a new array with results of applying the block to initial array elements

Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

suggestions = result.pluck(:suggestion)
# ["Lineman", "Linguist", "Librarian", "Lifeguard", "Line Cook", "Life Coach", "Life Guard"] 

This plucks all the suggestion values and returns them as an array.

2 Comments

If this is truly parsed JSON then this should be result.pluck('suggestion') as JSON is always parsed to String keys
Thanks sachin and vasfed.. it worked for me.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.