-1

Could someone please explain what I'm doing wrong.

fb = 2
fa = 100
def fc
    fa = fa - fb
end
puts "#{fa}"
fc
puts "#{fa}"
orde
  • 5,233
  • 6
  • 31
  • 33
H.Jason
  • 5
  • 3
  • What's the *exact* message it gives you, including the line number, when you run your example code? Telling us it's undefined is nice, but Ruby tells you more, so accurately tell us what it said as that is often significant. See [ask]. – the Tin Man Nov 05 '15 at 01:11

3 Answers3

1

Inside your fc method, the code does not know what fb is. In that context, both fa and fb are meaningless. (fa does not throw the same error since you are also doing assignment but that's besides the point).

To use fa and fb in your fc method, you need to pass them. Try this:

fb = 2
fa = 100

def fc(fa, fb)
  fa - fb
end

puts "#{fa}"

fa = fc(fa, fb)

puts "#{fa}"
yez
  • 2,368
  • 9
  • 15
1

fa and fb variables are not defined in the context of the fc method, so, the fc method does not know anything about them. You can't use outside scope's variables inside a method like that. You need to pass the required arguments to the fc method:

fb = 2
fa = 100

def fc(fa, fb) # fc method takes two arguments: fa and fb
    fa = fa - fb # Now, fc method knows about fa and fb variables/arguments
end

p fc(fa, fb) # pass fa and fb as arguments to the fc method
# => 98
K M Rakibul Islam
  • 33,760
  • 12
  • 89
  • 110
0

The function fc cannot use the variables fa or fb, as they're excluded from its scope (we say the function has no "closure" over those variables). A proc or lambda does have a closure:

    fb = 2
    fa = 100
    fc = proc {
        fa = fa - fb
    }
    puts "#{fa}"
    fc.call
    puts "#{fa}"
cliffordheath
  • 2,536
  • 15
  • 16