-2

I have an object variable that have the following value:

[
 {"a"=>nil, "b"=>79, "c"=>"mg/dL", "d"=>"high", "e"=>false},
 {"a"=>80, "b"=>139, "c"=>"mg/dL", "d"=>"low", "e"=>true},
 {"a"=>140, "b"=>199, "c"=>"mg/dL", "d"=>"moderate", "e"=>false}, 
 {"a"=>200, "b"=>nil, "c"=>"mg/dL", "d"=>"high", "e"=>false}
]

I am trying to pass the index and get the value of the key d but the code crash

object.as_json.each_with_index.map { |range, i| range[i].d }

I get undefined method d for the statement above

How can I get the values of "d"?

MatayoshiMariano
  • 2,026
  • 19
  • 23
User7354632781
  • 2,174
  • 9
  • 31
  • 54

2 Answers2

2

Access a hash value by using its key.

arr.map { |h| h["d"] } #=> ["high", "low", "moderate", "high"] 
Sagar Pandya
  • 9,323
  • 2
  • 24
  • 35
0

There is no need to use the methods as_json or each_with_index. Using only map is enough. See this answer, it explains how map works.

object.map { |element| element["d"] }

Instead of using the [] operator of the hash, you can also use fetch or dig. dig is available from ruby 2.3.

So it can be done like this using fetch: object.map { |element| element.fetch("d") }

You can pass an extra parameters to fetch, in case the key "d" is missing.

object.map { |element| element.fetch("d", "") }

If the key "d" is missing in some elements the string "" is used instead.

And using dig object.map { |element| element.dig("d") }

MatayoshiMariano
  • 2,026
  • 19
  • 23