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

developer098
  • 773
  • 2
  • 10
  • 18
  • 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. – jan.zikan Oct 31 '16 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. – Linuxios Oct 31 '16 at 19:30

1 Answers1

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)
Ursus
  • 29,643
  • 3
  • 33
  • 50
  • 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? – developer098 Oct 31 '16 at 19:36
  • 3
    In ruby there are these `callable objects`. Something like `puts_hello_word = lambda { puts "hello world" }` – Ursus Oct 31 '16 at 19:38
  • 2
    and call it with `puts_hello_word.call` – Ursus Oct 31 '16 at 19:38
  • Ok, I will look into that. Thank you for your time spent answering the question @Ursus. – developer098 Oct 31 '16 at 19:39