make hashtable out of 2 strings

N

notnorwegian

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?
 
R

Rolando Abarca

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,
 
P

Peña, Botp

From: (e-mail address removed) [mailto:[email protected]]=20
# 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'm currently playing w ruby1.9 now, so pls bear w me ;)

irb(main):001:0> s1 =3D "asdf"
=3D> "asdf"

irb(main):002:0> s2 =3D "bnmd"
=3D> "bnmd"

irb(main):004:0> pairs =3D s1.each_char.zip s2.each_char
=3D> #<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"]
=3D> nil

irb(main):006:0> pairs.map{|x|x}
=3D> [["a", "b"], ["s", "n"], ["d", "m"], ["f", "d"]]

irb(main):014:0> pairs.inject({}){|h,(k,v)| h[k]=3Dv; h}
=3D> {"a"=3D>"b", "s"=3D>"n", "d"=3D>"m", "f"=3D>"d"}

irb(main):029:0> pairs.map(&:reverse)
=3D> [["b", "a"], ["n", "s"], ["m", "d"], ["d", "f"]]

irb(main):032:0> pairs.map(&:first).join
=3D> "asdf"

kind regards -botp
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,202
Messages
2,571,057
Members
47,667
Latest member
DaniloB294

Latest Threads

Top