verdure
verdure

Reputation: 3341

How to display values from ruby hash

I have the following ruby hash:

values =  [ {"FA1": [{"Act 1": "A"},{"Act 2": "A"}] } ]

I need to iterate through the values array to get a string like this

cells = "[Act 1     A],[Act 2     B]"

Currently, I am trying this :

values[0]['FA1'].each do |key, val|
  cells = [#{key} #{val}]
end

which gives me the value of

#{key} as Act 1 A and #{val} as empty

And how can I append these values to a variable separated by a ','?

Upvotes: 1

Views: 2252

Answers (2)

megas
megas

Reputation: 21791

It's weird but anyway...

cells = []
values[0]['FA1'].each do |hash|
  hash.keys.each { |key| cells << "[#{key}   #{hash[key]}]" }
end
cells.join(",")

This will generate:

"[Act 1  A],[Act 2  A]"

Upvotes: 2

Dogbert
Dogbert

Reputation: 222128

Something like this should work:

values[0]['FA1'].first.map do |key, val|
  "#{key} #{val}"
end.join(",")

Upvotes: 1

Related Questions