Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting hash to string in Ruby

Tags:

arrays

ruby

hash

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?

like image 891
Jakub Troszok Avatar asked Jun 24 '09 13:06

Jakub Troszok


1 Answers

Hash includes Enumerable, so you can use collect:

flash.collect { |k, v| "<div class='#{k}'>#{v}</div>" }.join
like image 183
molf Avatar answered Oct 22 '22 01:10

molf