time = ["min", "sec"].collect {|i| {i=> Time.now.send(i).to_i}}

X

x1

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

#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
 
X

x1

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

:)


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

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

#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
 
A

ara.t.howard

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

#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']


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
 
X

x1

ah ok. Good point. I'm learning :)

Thanks so much ara!

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

#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']


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
 

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

Forum statistics

Threads
473,992
Messages
2,570,220
Members
46,805
Latest member
ClydeHeld1

Latest Threads

Top