Using the code below:
variable = puts "hello world".upcase
Why does Ruby automatically puts Hello world in upcase, without the variable first being invoked? I understand that you are setting the function to the variable, and if that variable is called it will return the return value (in this case, nil), but why is it that Ruby runs the method puts "hello world".upcase
almost without permission (have not called it, merely assigned to a variable)?
The Ruby language makes it easy to create functions. Your function can compute values and store them in local variables that are specific to the function. Those values can then be returned with the return statement. This would return the same value as the prior functions.
Ruby methods ALWAYS return the evaluated result of the last line of the expression unless an explicit return comes before it. If you wanted to explicitly return a value you can use the return keyword.
A method in Ruby is a set of expressions that returns a value. With methods, one can organize their code into subroutines that can be easily invoked from other areas of their program. Other languages sometimes refer to this as a function.
Ruby Class VariablesClass variables begin with @@ and must be initialized before they can be used in method definitions. Referencing an uninitialized class variable produces an error. Class variables are shared among descendants of the class or module in which the class variables are defined.
You are not assigning a function to a variable.
This is the same as
variable = (puts("hello world".upcase))
It needs to execute puts
to assign the returned value to the variable variable (lol).
This is a way to assign a method to a variable.
puts_method = method(:puts)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With