S Spooner
S Spooner

Reputation: 1

Accessing an array variable in Ruby

I'm currently teaching myself Ruby, via the 'Learn Ruby the Hard Way' course, and am having a problem referring to an array variable in a function.

On the section on while loops, it is required to turn a while-loop into a function, adjusting the while-loop parameters to be variables. My code:

#original while loop 
while i < 6 
  puts "At the top i is #{i}"
  numbers.push(i)
  i += 1
  puts "Numbers now: ", numbers
  puts "At the bottom i is #{i}"
end

#new function
number_array = [] 
def number_cruncher(number, cap)
  if number < cap
    puts "At the top number is #{number}"
    number_array.push(number)
    number += 1
    puts "Numbers now: ", number_array
    puts "At the bottom number is #{number}"
    number_cruncher(number, cap, number_array)
  end
end

number_cruncher(0,6)

Running this code gives a NameError, because number_array as cited in the function is an undefined local variable. I can understand that this is wrong, but I can't work out what variable scope or syntax would allow me to refer to a variable whose starting point is an empty array - except by specifying a variable 'number_array' as a parameter of the function, and then declaring number_array = [], which is functional, but seems overcomplicated.

I have researched variable scope in Ruby (here and elsewhere), but have nevertheless been unable to work this out.... Am 100% sure I am being really stupid, but help would nevertheless be appreciated!

Upvotes: 0

Views: 310

Answers (1)

Tom Lord
Tom Lord

Reputation: 28285

The normal approach would just be to make this a parameter with a default value:

def number_cruncher(number, cap, number_array = [])

You're also missing the crucial return value for the recursive function. You need to do something like this:

def number_cruncher(number, cap, number_array = [])
  return number_array if number >= cap # <-- !!!!!

  puts "At the top number is #{number}"
  number_array.push(number)
  number += 1
  puts "Numbers now: ", number_array
  puts "At the bottom number is #{number}"
  number_cruncher(number, cap, number_array)
end

Upvotes: 1

Related Questions