I want to output "Mr.Yuki" ...
1 def rename(name)
2 name = "Mr.#{name}"
3 end
4
5 name = "Yuki"
6 rename(name)
7 puts name
Yuki
In this syntax, the output will be "Yuki" without Mr..
1 def rname (name) # Variable name received by rename method name 2 name = "Mr. # {name}" # Variable name received by rename method name 3 end
A copy of the value passed as an argument is assigned to the variable of the method.
>~~~
5 name = "Yuki" #This name is all the argument name
6 rename(name)
7 puts name
>~~~
In short, the argument name and the variable name have the same name but are different.
Explanation step by step.
--Fifth line: The character string "Yuki" is assigned to the argument `name`.
--Line 6: Call method rename with this `name` as an argument
At this time, the value contained in `name` is copied.
--First line: The copied "Yuki" is assigned to the variable `name` of the method rename.
Therefore, the argument `name` and the variable` name` used in the method have the same value, and the value can be passed to the method.
--Second line: However, changing the value of the variable `name` does not affect the argument` name` because the argument `name` is different.
## So how do you get the results you expect?
Detailed explanation.
>~~~
1 def rename(name)
2 name = "Mr.#{name}"
3 end
>~~~
--Second line: In the method `rename`, the character string with Mr. added to the` name` received from the argument is returned as the return value to the method caller.
>~~~
6 name = rename(name)
>~~~
--Before the modification, you just called `rename (name)` and the method `rename`, but this time you are assigning` name = rename (name) `and the return value from the method to` name`.
1 def rename(name)
2 name = "Mr. # {name}" # ③ In response to the result of the 5th line, "Mr.Yuki" is assigned to name
on the left side
3 end
4
5 name = "Yuki" # ① Read the formula with one "=" from the right side. Assign "Yuki" to variable name
6 name = rename (name) # ② rename is the method on the first line. Assign the answer of this method and the value of the argument (name) (* defined in the 5th line) to the variable name on the left side.
7 puts name # ④ The return value is output by puts
Mr.Yuki
Now the value of `name` becomes a string with Mr. added by the method` rename`.
## at the end
It's really hard to understand here.
A lot of names come out. I couldn't understand it in my head.
I numbered the processes and showed them in order, and some came in.
It seems that a review is needed here.
Recommended Posts