Method parenthesis - beginner question

Hello,

I’m going through a book which presents an example from which I’m a bit
confused over.

Here’s the example;


class Person
def initialize(name)
set_name(name)
end

def name
@first_name + ’ ’ + @last_name
end

def set_name(name)
first_name, last_name = name.split(/\s+/)
set_first_name(first_name)
set_last_name(last_name)
end

def set_first_name(name)
@first_name = name
end

def set_last_name(name)
@last_name = name
end
end


If the name paranthesis input was something like “Jack S.”, then;

“first_name, last_name = name.split(/\s+/)” = first_name = Jack,
last_name = Smith.

Now here’s the confusion;

“set_first_name(first_name)” = I don’t quite understand this part. I
understand it becomes set_first_name(Jack), but then why is this;

" def set_first_name(name)" instead of " def
set_first_name(first_name)".

Is it basically putting the value of (first_name) into (name), so
set_first_name(name) = set_first_name(Jack)? If so, could someone
explain why it works like this?

Thanks.

Hi, Taz798 U,

Both " def set_first_name(name)" and " def set_first_name(first_name)"
is
fine. They are called formal parameter. See
http://en.wikipedia.org/wiki/Parameter_(computer_programming)#Parameters_and_argumentsfor
more information.

Yuanhang.

Thanks.

The (name) put me off, but I get it now :slight_smile:

Inside the method “set_name” “first_name” will be set to point to the
String “Jack” (in your example).

Then you are calling…

set_first_name(first_name)

Inside the set_first_name method, the name of the parameter is “name”.
So this reference to “Jack” is passed as the “name” parameter.

Now,
“first_name” inside the set_name method and
“name” inside the set_first_name method are
both pointing to the same object, the String “Jack”.

I think your point is valid because the parameter name could be
“first_name” to rhyme with the method name “set_first_name”.
But, no matter what you call it at all.

It could be something like

===
class Person
def initialize(name)
set_name(name)
end

def name
@first_name + ’ ’ + @last_name
end

def set_name(name)
first_name, last_name = name.split(/\s+/)
set_first_name(first_name)
set_last_name(last_name)
end

def set_first_name(first_name)
@first_name = first_name
end

def set_last_name(last_name)
@last_name = last_name
end
end

But, I think “name” is shorter!

Abinoam Jr.

Thanks Abinoam Jr.

That makes it more clearer as the book (up to that point) hadn’t really
properly explain parameter usage. I was initially wondering how
set_first_name(first_name) could become set_first_name(name), but now I
understand that they’re both pointing to the same object.