1

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 Answers 2

1

In Ruby, when a method is defined, it gets its own scope with its own set of local variables, so any local variable defined outside that method does not exist.

You can solve this by turning your variable into an instance variable:

#!/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

This works because translate() is considered a method of the "main" Object (since it was declared in main), so you can access any instance variables also declared in the "main" Object.

Sign up to request clarification or add additional context in comments.

Comments

0

just declare numHash = {} as global variable

$numHash = {}

now use $numHash elsewhere in the code

Global variables in Ruby are accessible from anywhere in the Ruby program, regardless of where they are declared. Global variable names are prefixed with a dollar sign ($).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.