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

2
  • 1
    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. Commented Oct 31, 2016 at 19:22
  • 1
    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. Commented Oct 31, 2016 at 19:30

1 Answer 1

14

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)
Sign up to request clarification or add additional context in comments.

4 Comments

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?
In ruby there are these callable objects. Something like puts_hello_word = lambda { puts "hello world" }
and call it with puts_hello_word.call
Ok, I will look into that. Thank you for your time spent answering the question @Ursus.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.