i have 2 strings, i want to take for each char in string1 the same
indexed char in string2 and make them into a key->value pair.
how can i iterate a string?
i have 2 strings, i want to take for each char in string1 the same
indexed char in string2 and make them into a key->value pair.
how can i iterate a string?
On May 26, 2008, at 10:14 PM, [email protected] wrote:
i have 2 strings, i want to take for each char in string1 the same
indexed char in string2 and make them into a key->value pair.how can i iterate a string?
something like this?
s1 = “asdf”
=> “asdf”s2 = “bnmd”
=> “bnmd”arr = s1.split(//).zip(s2.split(//))
=> [[“a”, “b”], [“s”, “n”], [“d”, “m”], [“f”, “d”]]h = Hash[*arr.flatten]
=> {“a”=>“b”, “d”=>“m”, “f”=>“d”, “s”=>“n”}
regards,
From: [email protected] [mailto:[email protected]]
i’m currently playing w ruby1.9 now, so pls bear w me
irb(main):001:0> s1 = “asdf”
=> “asdf”
irb(main):002:0> s2 = “bnmd”
=> “bnmd”
irb(main):004:0> pairs = s1.each_char.zip s2.each_char
=> #Enumerable::Enumerator:0xbb69d0
i like the flexibility of enums, so you can do
irb(main):005:0> pairs.each {|x| p x}
[“a”, “b”]
[“s”, “n”]
[“d”, “m”]
[“f”, “d”]
=> nil
irb(main):006:0> pairs.map{|x|x}
=> [[“a”, “b”], [“s”, “n”], [“d”, “m”], [“f”, “d”]]
irb(main):014:0> pairs.inject({}){|h,(k,v)| h[k]=v; h}
=> {“a”=>“b”, “s”=>“n”, “d”=>“m”, “f”=>“d”}
irb(main):029:0> pairs.map(&:reverse)
=> [[“b”, “a”], [“n”, “s”], [“m”, “d”], [“d”, “f”]]
irb(main):032:0> pairs.map(&:first).join
=> “asdf”
kind regards -botp
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs