Using Functions To Return Something

So I managed to write a simple function and use return and puts to display it.

def add(a, b) 
  puts "ADDING #{a} + #{b}" 
  return a + b 
end 

age = add(30, 5) 

puts "Age: #{age}" 

Display :

CaiGengYangs-MacBook-Pro:GoatBoy CaiGengYang$ ruby ex80.rb 
ADDING 30 + 5 
Age: 35 

But when I tried to extend it to (A+B)/C, it display error message :

def add(a, b) 
  puts "(ADDING #{a} + #{b}) / #{c}" 
  return (a + b) / c 
end 

age = add(30, 10) / 5 

puts "Age: #{age}" 

Display :

CaiGengYangs-MacBook-Pro:GoatBoy CaiGengYang$ ruby ex90.rb 
ex90.rb:2:in `add': undefined local variable or method `c' for main:Object (NameError) 
        from ex90.rb:6:in `<main>'' 

Any smart person over here ? Help lah …

Gengyang

This is what I did :

I created a file and saved it as ex50.rb —

def add(a, b, c) 
  puts "(ADDING #{a} + #{b}) / #{c}" 
  return (a + b) / c 
end 

age = add(30, 10) / 5 

puts "Age: #{age}"

Then I tried to run it :
CaiGengYangs-MacBook-Pro:~ CaiGengYang$ ruby ex50.rb
But I got this error message :
ruby: No such file or directory -- ex50.rb (LoadError)

As has been expressed in other posts, you really need to get to know the terminal, before doing these kind of exercises.

The above post clearly states that you do not have a file called ex50.rb in your current working directory, so you can’t expect to be able to run it.

Have a look at something like Getting to know the Terminal Part 1: Basic File Operations - Blog - Digital Rebellion to get the basics.


For your Ruby code, you are defining a method add which takes three arguments, a, b, and c, however when you are calling it, you only supply two arguments (30 and 10). You need to give it three arguments. It seems as if you line:

age = add(30, 10) / 5

should have been

age = add(30, 10, 5)

instead, as it seems that you want the result to be (30 + 10) / 5 (which results to 8)

3 Likes