This forum is now read-only. Please use our new forums! Go to forums
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
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.
Answer 553d8f58937676893d0002a8
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.
Popular free courses
- Free Course
Learn SQL
In this SQL course, you'll learn how to manage large datasets and analyze real data using the standard data management language.Beginner friendly,4 LessonsLanguage Fluency - Free Course
Learn JavaScript
Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.Beginner friendly,11 LessonsLanguage Fluency - Free Course
Learn HTML
Start at the beginning by learning HTML basics — an important foundation for building and editing web pages.Beginner friendly,6 LessonsLanguage Fluency
2 comments
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.
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.