2010/1/21 Ruby Newbee said:
class Array
=A0def atoh
=A0 =A0 hash =3D Hash.new
=A0 =A0 if size % 2 !=3D 0
=A0 =A0 =A0 =A0 raise "size must be odd"
=A0 =A0 end
=A0 =A0 0.step(size-1,2) do |c| hash[self[c]] =3D self[c+1] end
=A0 =A0 hash
=A0end
end
You are aware that there is Hash[] already, are you?
irb(main):004:0> a=3D%w{foo bar baz buz}
=3D> ["foo", "bar", "baz", "buz"]
irb(main):005:0> Hash[*a]
=3D> {"foo"=3D>"bar", "baz"=3D>"buz"}
Btw, you can shorten your method by using #each_slice. I would do it like =
this:
irb(main):008:0> module Enumerable
irb(main):009:1> def to_hash
irb(main):010:2> h=3D{}
irb(main):011:2> each_slice(2) {|k,v| raise "size must be odd" if v.nil?;h[=
k]=3Dv}
irb(main):012:2> h
irb(main):013:2> end
irb(main):014:1> end
=3D> nil
irb(main):015:0> a.to_hash
=3D> {"foo"=3D>"bar", "baz"=3D>"buz"}
irb(main):016:0> a[0...-1].to_hash
RuntimeError: size must be odd
from (irb):11:in `block in to_hash'
from (irb):11:in `each_slice'
from (irb):11:in `to_hash'
from (irb):16
from /opt/bin/irb19:12:in `<main>'
irb(main):017:0>
Disadvantage: it is not as safe as your solution because it will
detect an error even for Arrays with even number of elements if any
value is nil.
Advantage: it works for all Enumerables.
Synthesis:
module Enumerable
def to_hash
h =3D {}
key =3D flag =3D nil
each do |val|
if flag
h[key] =3D val
else
key =3D val
end
flag =3D !flag
end
raise 'odd!' if flag
h
end
end
For "size" in the code above, we know it's a self.size method actually.
But how ruby differ it's a variable or an instance method?
As soon as Ruby has seen an assignment it assumes a local variable. Try th=
is:
ruby -e 'def f;123;end;def g;p f;f=3D0;p f;end;g'
More details can be found here:
http://www.ruby-doc.org/docs/ProgrammingRuby/html/language.html#UO
Kind regards
robert
--=20
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/