Array#to_h example fails


#1

Using this example from the documentation, results in error:

[“foo”, “bar”].to_h {|s| [s.ord, s]}

Traceback (most recent call last):
3: from /Volumes/Radha/Users/rob/.rvm/rubies/ruby-2.5.3/bin/irb:11:in <main>' 2: from (irb):37 1: from (irb):37:into_h’
TypeError (wrong element type String at 0 (expected array))

I have tried this on 2.6.0-preview 2 and 2.5.3.
Why am I getting this error?


#2

A basic practice to debug is to test, the different part of an expression.

for start. try : print [“foo”, “bar”].to_h

it might be the problematic part depending of our version of ruby.


#3

Tried this:

[“foo”, “bar”].to_h

and got: NameError (undefined local variable or method `“foo”’ for main:Object)

As a newbie, I’m not grokking this.
The example I gave was out of the documentation.
Is the documentation wrong?
What am I missing?
Read Benjamin’s blog article, but no further ahead.


#4

…to_h is a new function of ruby. If your version of Ruby is older than 2.0,0. It won’t work !

the safe approach is this one:

#!/usr/bin/env ruby

require 'pp'

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

pp array
pp hash

PS
array = %w(cat hat bat mat) is the same thing than

array = [ “cat” , “hat” , “bat” , “mat” ]


#5

Yes, understand it’s new, but, as I stated, I tested this with 2.6.0-preview2 and 2.5.3.
Again, my question is this: “Is the documentation incorrect or is there a bug?”

I understand your “safe” approach, but surely a documentation example should work?


#6

Yes and No , because the function is buggy.


#7

I made a verification and the example seem to be the problem.

This function need 2 arrays.

p [[:foo, :bar], [1, 2]].to_h

=> {:foo => :bar, 1 => 2}

https://ruby-doc.org/core-2.1.0/Array.html#method-i-to_h


#8

Thanks for clearing this up. Much appreciated.
I’m surprised that the documentation example hasn’t been flagged before this.