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

def subtract(a, b)
    puts "SUBTRACTING #{a} - #{b}"
    a - b

Here is my code and my question is, why do I need the extra (a + b) and (a - b) at the end? I understand that "def" is setting up the function and the 'puts "ADDING #{a} + #{b}"' is placing that code on to the screen for me to see. By why can't the system just see the way the code is placed in "puts".

I'm sorry if this is a bit confusing, but I am new to ruby. Also when I edit the a + b it won't allow me to do so. Is there a way I can edit it so that it reads the number on one line and then the other on another line. Or perhaps so that the a + b comes out as a...+...b (imagine the "." are empty spaces.)

mongobongo
  • 171
  • 12

2 Answers2

2

You need it at the end because "puts" sends that string to the console whereas the a+b at the end is the return value of the def.

It would be the equivalent of doing this in javascript:

function myFunc(a,b) {
 console.log("adding" + a + " + " + b);
 return a+b;
}
Charles
  • 1,121
  • 19
  • 30
2

It is interpreting the "ADDING #{a} + #{b}" as a string, as it should. It is a string. It doesn't parse your strings and assume what you mean. Then it prints it to the output using puts. puts is an expression that returns nil, not the value of a + b (thanks Jörg W Mittag). The a+b is an expression with the value of the value of a plus the value of b so then your function has that value as well.

In C it is the difference between

void add( int a, int b )
{
    printf( "ADDING %d + %d\n", a, b );
}

and

int add( int a, int b )
{
    printf( "ADDING %d + %d\n", a, b );
    return a + b;
}
clcto
  • 9,530
  • 20
  • 42
  • Everything in Ruby is an expression. `puts` is just method call like any other method call, and like any other method call, it returns the return value of the method. In the case of `puts`, the return value is `nil`. – Jörg W Mittag Aug 29 '13 at 02:21
  • editted, haven't worked with ruby – clcto Aug 29 '13 at 04:18