Ruby def function cannot define local variable


#1



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
  translate
end


translate


#2

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)
  ...
end

numHash = {}
translate(numHash)

Hopefully that makes sense!


#3

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


#4

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.


#5

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!


#6

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