developer098
developer098

Reputation: 843

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

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)?

Upvotes: 8

Views: 9626

Answers (1)

Ursus
Ursus

Reputation: 30071

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)

Upvotes: 14

Related Questions