I was going through the Exception Handling chapter of the Bastards Book of Ruby and I came across a bit of code in between the lines of:
while 1
puts "Enter a number>>"
num = Kernel.gets.match(/\d+/)[0]
puts "#{num} + 1 is: #{num.to_i + 1}"
end
I'm unable to grasp the purpose of [0]
appended to the match method in the num
variable. What does it do here?
I'm unable to grasp the purpose of
[0]
In Ruby, [0]
is a method call. What a method does depends on the receiver. In addition, arrays are objects, too. Unlike other languages, there are no "primitive types" in Ruby. Each value you're dealing with, is an object.
Your line contains a method chain consisting of 3 method calls:
Kernel.gets.match(/\d+/)[0]
# └──┘ └──────────┘└─┘
# 1 2 3
In a method chain, one method's return value becomes the next method's receiver. Let's examine each one to figure out what []
we have here:
Kernel#gets
returns an instance of String
(or nil
)String#match
returns an instance of MatchData
(or nil
)MatchData#[]
returns a specific match (or nil
)In your case, [0]
returns the first match, e.g.:
input = "123\n" # <- this could be the return value from Kernel.gets
#=> "123\n"
match = input.match(/\d+/)
#=> #<MatchData "123">
match[0]
#=> "123"