0 points
Submitted by ignatdd
over 6 years

Question about 10/19

The code is :

method that capitalizes a word

def capitalize(string) puts “#{string[0].upcase}#{string[1..-1]}” end

capitalize(“ryan”) # prints “Ryan” capitalize(“jane”) # prints “Jane”

block that capitalizes each string in the array

[“ryan”, “jane”].each {|string| puts “#{string[0].upcase}#{string[1..-1]}”} # prints “Ryan”, then “Jane”

can someone explain what the #{string[1..-1]} part does please? I understand that it makes it so that the string has only the first letter of the first word capitalized, but can someone elaborate on this idea please? I do not understand the 1..-1 part.

Thanks!

Answer 5505828951b88785f80061a4

5 votes

Permalink

It’s explained in the “hint“ section:

string[0] refers to the first character in the string; string[1..-1] refers to the range of the second through final characters. Therefore, the method prints out the capitalized version of the first character and prints the second through final characters as-is.

Notice that string[0] is attached to .upcase, whereas string[1..-1] is not.

points
Submitted by vava
over 6 years

Answer 553d8f58937676893d0002a8

1 vote

Permalink

1..-1 looks like it should be a syntax error.. it seems like it should be 1..3 for the name Ryan or Jane since there are 4 letters total in both names.

Is the -1 a way of telling Ruby “second letter through the rest of the string“ ? Obviously, we can’t predict how many characters will be passed to the block.

points
Submitted by Volcania
over 6 years

2 comments

Maesj over 6 years

Actually -1 is whatever number is at the end of an array. An array starts with 0 and ends with -1, so if you have [1, 2, 3] in an array, 1 is at place 0 right? 2 is at place 1, and 3 is at place 2. BUT, 3 is also at place -1, 2 is also at place -2, and 1 is also at place -3 :) it’s weird at first, but basically just means that you can count from front to back or back to front in an array.

Teesh Yalamanchili about 6 years

Thanks for this response. It REALLY is a goofy thing that Ruby does. In python you’d grab the length of the array and go from 1 to the length. Seems Ruby tried to make it easier by using negative numbers with -1 being the last item in the array but counting from 1..-1 is not very intuitive.