rainbowsorbet
rainbowsorbet

Reputation: 563

How to iterate through a Hashie::Mash?

I'd like to loop through the keys and values of a Hashie::Mash.

Here's my attempt to do so:

html = "Just look at these subscriptions!"
client.subscriptions.each do |sub|
  html << sub.each do |key, value|
      html << key.to_s
      html << " = "
      html << value.to_s
  end
end

It returns the following error:

"Can't convert Hashie::Mash to String (Hashie::Mash#to_str gives NilClass)"

I've tried sub.keys.to_s and sub.values.to_s which produced ["key1", "key2", "key3"], ["value1", "value2", "value3"], but I'm looking for something that shows the pairs matched, as they are in a hash, or like ["key1: value1", "key2: value2", "key3: value3"]. Is there a way to do this without zipping together separate arrays?

Thanks!

Upvotes: 3

Views: 2241

Answers (1)

Amadan
Amadan

Reputation: 198294

sub.to_hash shows something that is exactly like a hash. :) Then you can do whatever you can do with a hash; like

html << sub.to_hash.to_s

or you could do what you're doing, in a bit more Rubyish way:

html << sub.map { |key, value| "#{key} = #{value}" }.join(", ")

However, your real problem is in html << sub.each ...: each returns the collection being iterated, so you're doing html << sub; and this fails. Your code would work if you just removed html << from that line, since the concatenation is taken care of inside the each loop.

Upvotes: 3

Related Questions