Ruby def function cannot define local variable


I'm not stuck at a particular exercise.

I cannot get my def function to recognize the hash(dictionary) that comes before it. I'm familiar with Python and cannot get the same thing to work with Ruby.

Here is my error:
./engEsp.rb:12:in translate': undefined local variable or methodnumHash' for main:Object (NameError)
from ./engEsp.rb:19:in `'

Here is the program...

#!/usr/bin/env ruby

system "clear"

numHash = {}

def translate
  print "Number in English: "
  eng = gets.chomp
  print "Numero en Espanol: "
  esp = gets.chomp
  numHash[eng] = esp
  puts "Data has been added!"
  puts numHash



In order to have access to numHash within the translate method, you'd have to pass it into the method as an argument.

def translate(numHash)

numHash = {}

Hopefully that makes sense!


Aye. Thanx. I'm still getting around some of the weird things with Ruby. It's different than Python.


I just found out from someone on stackoverflow that a hash cannot be called outside of a method unless it's a "global variable" or "instance variable". So my code can stay the same as I originally posted just prefix numHash with either @numHash or $numHash and there is no need for passing arguments.


Yeah, that's another way of doing things. What this means is that @numHash would be an instance variable of main (which is an instance of the class Object) in Ruby. As long as you can get your code working at this stage, that's the main thing!


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.