
-----------------------------------
Tony
Fri Oct 13, 2006 11:38 am

formating / traversing hash
-----------------------------------
given a hash of keys => values, I want to construct a conditional statement that the hash describes, in the form "a = b AND c = d", etc. So far I've came up with

irb(main):001:0> foo = {"a"=>"b","c"=>"d"}
=> {"a"=>"b", "c"=>"d"}
irb(main):002:0> bar = ""
=> ""
irb(main):003:0> foo.each{|key, value|
irb(main):004:1* bar = "#{bar} #{key} = #{value} AND" }
=> {"a"=>"b", "c"=>"d"}
irb(main):005:0> bar.slice!(0..-4)
=> " a = b AND c = d "

which seems like a pretty ugly solution. I especially don't like that last hack on a leftover "AND". Is there a more eligant approach?

While #collect gives me a nice array

irb(main):007:0> foo.collect
=> [["a", "b"], ["c", "d"]]

the #join acts as if the array was flattened

irb(main):006:0> foo.collect.join("*")
=> "a*b*c*d"

 :?

-----------------------------------
wtd
Fri Oct 13, 2006 11:51 am


-----------------------------------
What happens if you pass a block to collect?  :)

-----------------------------------
Tony
Fri Oct 13, 2006 12:00 pm


-----------------------------------

irb(main):025:0> bar = foo.collect{|a| a.join("=")}.join(" AND ")
=> "a=b AND c=d"

excellent question, thank you :D

-----------------------------------
wtd
Fri Oct 13, 2006 12:10 pm


-----------------------------------

irb(main):025:0> bar = foo.collect{|a| a.join("=")}.join(" AND ")
=> "a=b AND c=d"

excellent question, thank you :D

You're welcome, though I would have said:

foo.collect { |k, v| "#{k} = #{v}" }.join(" AND ")
