Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is [0] and [1..-1] in Ruby?

Tags:

ruby

What do [0] and [1..-1] mean in the following code?

def capitalize(string) 
  puts "#{string[0].upcase}#{string[1..-1]}"
end
like image 706
AnisXTN Avatar asked Dec 18 '22 01:12

AnisXTN


1 Answers

string[0] is a new string that contains the first character of string.
It is, in fact, syntactic sugar for string.[](0), i.e. calling the method String#[] on the String object stored in the variable string with argument 0.

The String#[] method also accepts a Range as argument, to extract a substring. In this case, the lower bound of range is the index where the substring starts and the upper bound is the index where the substring ends. Positive values count the characters from the beginning of the string (starting with 0), negative values count the characters from the end of the string (-1 denotes the last character).

The call string[1..-1] (string.[](1..-1)) returns a new string that is initialized with the substring of string that starts with the second character of string (1) and ends with its last character.

Put together, string[0].upcase is the uppercase version of the first character of string, string[1..-1] is the rest of string (everything but the first character).

Read more about different ways to access individual characters and substrings in strings using String#[] method.

like image 189
axiac Avatar answered Jan 06 '23 08:01

axiac