Time = .collect {|i| {i=> Time.now.send(i).to_i}}

What’s the best way to make the first item below yield a hash instead
of an array in one line? I’m struggling :frowning:

#doesnt work
time = [“min”, “sec”].collect {|i| {i=> Time.now.send(i).to_i}}
puts time.type # Array

#works
time = [“min”, “sec”].collect {|i| {i=> Time.now.send(i).to_i}}.first
puts time.type # Hash
puts time[‘min’]

Thanks in advance

Sorry --Subject was supposed to be “Need help creating hash from an
array”

ok…nvrmind… I think I got it:
time = Hash[*[“min”, “sec”].collect { |i| [i, Time.now.send(i)]}.flatten]

:slight_smile:

On Fri, 1 Dec 2006, x1 wrote:

puts time[‘min’]
harp:~ > cat a.rb
now = Time.now
h = %w( min sec ).inject({}){|h,k| h.update k => now.send(k).to_i}

p h

harp:~ > ruby a.rb
{“sec”=>44, “min”=>26}

in particular you don’t want to call Time.now inside the loop: you’ll
otherwise
sometimes get

{“sec”=>0, “min”=>42}

when you should have gotten

{“sec”=>59, “min”=>41}

regards.

-a

ah ok. Good point. I’m learning :slight_smile:

Thanks so much ara!