Could someone please explain what I'm doing wrong.
fb = 2
fa = 100
def fc
fa = fa - fb
end
puts "#{fa}"
fc
puts "#{fa}"
Could someone please explain what I'm doing wrong.
fb = 2
fa = 100
def fc
fa = fa - fb
end
puts "#{fa}"
fc
puts "#{fa}"
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}"
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
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}"