How do I split a key in hashes in Rails?

ruby-on-rails arrays hash key-value

262 просмотра

1 ответ

40 Репутация автора

I want to break the key as I want to compare their values. Below 63 represents id, rest is time.

[63, Thu, 14 Jul 2016 09:01:14 UTC +00:00]=>3.0
Автор: s_a Источник Размещён: 18.07.2016 01:12

Ответы (1)


0 плюса

887 Репутация автора

Решение

Ruby can extract all parts of key and value for you if you provide enough block parameters.

I assume your hash is stored in a variable named hash.

If you specify only two parameters, Ruby will put the key in the first one and the value in the second one.

hash.each do |key, value|
  puts key # prints [63, Thu, 14 Jul 2016 09:01:14 UTC +00:00]
  puts value # prints 3.0
end

But Ruby can also expand the key for you. In your key, you have 2 values. So you need to give 2 block parameters, in braces:

hash.each do |(id, time), value|
  puts id # prints 63
  puts time # prints Thu, 14 Jul 2016 09:01:14 UTC +00:00
  puts value # prints 3.0
end

You can give the block parameters any names you like.

Автор: Ilya Vassilevsky Размещён: 18.07.2016 03:30
Вопросы из категории :
32x32