Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 formating / traversing hash
Index -> Programming, Ruby -> Ruby Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
Tony




PostPosted: Fri Oct 13, 2006 11:38 am   Post subject: 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
code:

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
code:

irb(main):007:0> foo.collect
=> [["a", "b"], ["c", "d"]]

the #join acts as if the array was flattened
code:

irb(main):006:0> foo.collect.join("*")
=> "a*b*c*d"

Confused
Latest from compsci.ca/blog: Tony's programming blog. DWITE - a programming contest.
Sponsor
Sponsor
Sponsor
sponsor
wtd




PostPosted: Fri Oct 13, 2006 11:51 am   Post subject: (No subject)

What happens if you pass a block to collect? Smile
Tony




PostPosted: Fri Oct 13, 2006 12:00 pm   Post subject: (No subject)

code:

irb(main):025:0> bar = foo.collect{|a| a.join("=")}.join(" AND ")
=> "a=b AND c=d"

excellent question, thank you Very Happy
Latest from compsci.ca/blog: Tony's programming blog. DWITE - a programming contest.
wtd




PostPosted: Fri Oct 13, 2006 12:10 pm   Post subject: (No subject)

Tony wrote:
code:

irb(main):025:0> bar = foo.collect{|a| a.join("=")}.join(" AND ")
=> "a=b AND c=d"

excellent question, thank you Very Happy


You're welcome, though I would have said:

code:
foo.collect { |k, v| "#{k} = #{v}" }.join(" AND ")
Display posts from previous:   
   Index -> Programming, Ruby -> Ruby Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 4 Posts ]
Jump to:   


Style:  
Search: