class Array
def atoh
hash = Hash.new
if size % 2 != 0
raise "size must be odd"
end
0\.step\(size\-1,2\) do |c| hash\[self\[c\]\] = self\[c\+1\] end
hash
end
end
You are aware that there is Hash already, are you?
irb(main):004:0> a=%w{foo bar baz buz}
=> ["foo", "bar", "baz", "buz"]
irb(main):005:0> Hash[*a]
=> {"foo"=>"bar", "baz"=>"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={}
irb(main):011:2> each_slice(2) {|k,v| raise "size must be odd" if v.nil?;h[k]=v}
irb(main):012:2> h
irb(main):013:2> end
irb(main):014:1> end
=> nil
irb(main):015:0> a.to_hash
=> {"foo"=>"bar", "baz"=>"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 = {}
key = flag = nil
each do |val|
if flag
h[key] = val
else
key = val
end
flag = !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 this:
ruby -e 'def f;123;end;def g;p f;f=0;p f;end;g'
More details can be found here:
http://www.ruby-doc.org/docs/ProgrammingRuby/html/language.html#UO
Kind regards
robert
···
2010/1/21 Ruby Newbee <rubynewbee@gmail.com>:
--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/