Search code examples
rubyhasheachenumerate

Ruby Hash: type casting


I’m trying to get a better grasp on writing in Ruby and working with Hash tables and their values.

1. Say you have a hash:

‘FOO’= {‘baz’ => [1,2,3,4,5]}

Goal: convert each value into a string in the ‘Ruby’ way.

I’ve come across multiple examples of using .each eg.

FOO.each = { |k,v| FOO[k] = v.to_s } 

However this renders an array encapsulated in a string. Eg. "[1,2,3,4,5]" where it should be ["1", "2", "3", "4", "5"].

2. When type casting is performed on a Hash that’s holds an array of values, is the result a new array? Or simply a change in type of value (eg. 1 becomes “1” when .to_s is applied (say the value was placed through a each enumerator like above).

An explanation is greatly appreciated. New to Ruby.


Solution

  • In the each block, k and v are the key value pair. In your case, 'baz' is key and [1,2,3,4,5] is value. Since you're doing v.to_s, it converts the whole array to string and not the individual values.

    You can do something like this to achieve what you want.

    foo = { 'baz' => [1,2,3,4,5] }
    foo.each { |k, v| foo[k] = v.map(&:to_s) }