Robin
Robin

Reputation: 69

Modifying an Array

I have an Array like this

example_array = ['dog', 'cat', 'snake']

And I am trying to append the timestamp to each element of the array and the output should look like

example_array = [{'dog': 'time_stamp'},{'cat':'time_stamp'},{'snake':'time_stamp'}]

I've tried this but the output is incorrect:

a = {}
example_array.each_with_index do |element, i|
  a.merge!("#{element}": "#{Time.now}")
  example_array.delete_at(i)
end

Can anyone suggest me a solution in ruby? I have tried a lot of ways but couldn't obtain the output like above.

Upvotes: 0

Views: 127

Answers (4)

Cary Swoveland
Cary Swoveland

Reputation: 110755

example_array.product([Time.now]).map { |k,v| { k.to_sym=>v }}
  #=> [{:dog=>2018-02-27 20:42:56 -0800},
  #    {:cat=>2018-02-27 20:42:56 -0800},
  #    {:snake=>2018-02-27 20:42:56 -0800}

]Note this ensures that all values (timestamps) are equal.

Upvotes: 1

sawa
sawa

Reputation: 168269

['dog', 'cat', 'snake'].map{|e| [{e.to_sym => "time_stamp"}]}
# => [[{:dog=>"time_stamp"}], [{:cat=>"time_stamp"}], [{:snake=>"time_stamp"}]]

Upvotes: 0

iceveda06
iceveda06

Reputation: 619

Aditha,

How about this?

array = ["cat", "hat", "bat", "mat"]
hash = []
hash.push(Hash[array.collect { |item| [item, Time.now] } ])

OUTPUT: => [{"cat"=>"2018-02-28 04:23:08 UTC", "hat"=>"2018-02-28 04:23:08 UTC", "bat"=>"2018-02-28 04:23:08 UTC", "mat"=>"2018-02-28 04:23:08 UTC"}]

Instead of item.upcase you would insert your timestamp info. It gives me hashes inside of array.

Upvotes: 1

Egor Egorov
Egor Egorov

Reputation: 765

only weird thing is that you have to use => instead of :

arr = ['dog', 'cat', 'snake']
arr2 = []

for index in 0 ... arr.size
  arr2.push({arr[index] => Time.now})
end

puts arr2

Upvotes: 0

Related Questions