9

Let's say we have a hash:

flash = {}
flash[:error] = "This is an error."
flash[:info] = "This is an information."

I would like to convert it to a string:

"<div class='error'>This is an error.</div><div class='info'>This is an information".

in nice one liner ;)

I found something like that:

flash.to_a.collect{|item| "<div class='#{item[0]}'>#{item[1]}</div>"}.join

That solves my problem but maybe there is nicer solution built in hashtable class?

Jakub Troszok
  • 99,267
  • 11
  • 41
  • 53

5 Answers5

25

Hash includes Enumerable, so you can use collect:

flash.collect { |k, v| "<div class='#{k}'>#{v}</div>" }.join
molf
  • 73,644
  • 13
  • 135
  • 118
0

You can get the keys in the hash using

flash.keys

and then from there you can build a new array of strings and then join them. So something like

flash.keys.collect {|k| "<div class=#{k}>#{flash[k]}</div>"}.join('')

Does that do the trick?

Bryan Ward
  • 6,443
  • 8
  • 37
  • 48
0

inject is infinitely handy:

flash.inject("") { |acc, kv| acc << "<div class='#{kv[0]}'>#{kv[1]}</div>" }
Ray Vernagus
  • 6,130
  • 1
  • 24
  • 19
0
[:info, :error].collect { |k| "<div class=\"#{k}\">#{flash[k]}</div>" }.join

The only problem with solutions presented so far is that you usually need to list flash messages in particular order - and hash doesn't have it, so IMHO it's better use pre-defined array.

Lukas Stejskal
  • 2,542
  • 19
  • 30
  • You can also use Ruby 1.9, or borrow ActiveSupport's `OrderedHash` if you require Ruby 1.8. – molf Jun 15 '10 at 12:48
0

Or maby?

class Hash
  def do_sexy
    collect { |k, v| "<div class='#{k}'>#{v}</div>" }.flatten
  end
end

flash = {}
flash[:error] = "This is an error."
flash[:info] = "This is an information."

puts flash.do_sexy

#outputs below
<div class='error'>This is an error.</div>
<div class='info'>This is an information.</div>
Simon Gate
  • 582
  • 2
  • 9