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

1

8

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

Marquet answered 31/10, 2016 at 19:17 Comment(2)
You are not assigning function to variable. You are assigning return value of function to variable so the function runs first so you get the value for assignment.Nourishing
Ruby doesn't have pure first-class functions like Python or JavaScript. In Python, you have to call a function -- foo is a reference to the function object foo, and foo() is a call to that function. In Ruby, foo is a call to the function -- other syntax is needed to get a Method object.Article
P
13

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)
Proliferous answered 31/10, 2016 at 19:22 Comment(4)
I've tried to put in method = puts(:hello), but it like the other variable example just runs similarly without permission. Could you provide an example using puts "hello world" where it would store the method within the variable without running it?Marquet
In ruby there are these callable objects. Something like puts_hello_word = lambda { puts "hello world" }Proliferous
and call it with puts_hello_word.callProliferous
Ok, I will look into that. Thank you for your time spent answering the question @Ursus.Marquet

© 2022 - 2024 — McMap. All rights reserved.