Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Ruby, if you assign a function to a variable, why does it automatically run?

Tags:

methods

ruby

irb

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".upcasealmost without permission (have not called it, merely assigned to a variable)?

like image 599
developer098 Avatar asked Oct 31 '16 19:10

developer098


People also ask

How do functions work in Ruby?

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.

How does a function return a value in Ruby?

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.

What happens when you call a method in Ruby?

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.

How are variables declared in Ruby?

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.


1 Answers

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)
like image 139
Ursus Avatar answered Oct 13 '22 02:10

Ursus