Beginner Q- variable = method.method

Hi !
I was wondering the logic behind :
name = gets.chomp
I start to learn Ruby and it seems easy to understand we can set a value
to a variable or even a value that we want to “.gets” and “.chomp” but
how can we set directly a method (or several methods) to a variable.
To compare this to the English language I don’t quit understand a
definition which state : a noun = a verb.

Thanks in advance for your insight!

If you’re starting with Ruby, you should probably leave assigning
methods to variables until later; once you’ve learned more about the
rest of the language.

The reason to keep a method inside a variable would usually be so that
you can pass it between objects and manipulate it. That’s
metaprogramming, which should probably be left alone until you have a
firm grasp of programming.

Here’s a way of calling a method without having to directly use the
class that the method belongs to:

class A
def a
puts 1
end
end

a_class = A.new

a_class.a
1
=> nil

method = a_class.method(:a)
=> #<Method: A#a>

method.call
1
=> nil

Programming languages are not English. When you write

x = abc

ruby evaluates the right hand and assigns the result to x.

Ruby allows you to be brief, but you can rewrite your example as
follows:

input = Kernel.gets()
name = input.chomp()

gets is a class method of the Kernel class, returning a String object,
the next input line.

http://ruby-doc.org/core-2.3.0/Kernel.html#method-i-gets

chomp is a method defined on instances of the String class, returning a
new String object, the chomped line.

The method is called gets because it gets (and return) an input line. It
is called chomp because it chomps the string.

If you need to assign methods to a variable, you can do:

m1 = Kernel.method(:gets)
m2 = String.instance_method(:chomp)
m3 = m2.bind(“hello world”)
m4 = “hello world”.method(:chomp)

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs