[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

make hashtable out of 2 strings

slix

5/27/2008 2:13:00 AM

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?
2 Answers

Rolando Abarca

5/27/2008 2:25:00 AM

0

On May 26, 2008, at 10:14 PM, notnorwegian@yahoo.se 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,
--
Rolando Abarca M.


Peña, Botp

5/27/2008 2:55:00 AM

0

From: notnorwegian@yahoo.se [mailto:notnorwegian@yahoo.se]=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