Using block query


#1

How Blocks Differ from Methods

ref the following code:

[“ryan”, “jane”].each {|string| puts “#{string[0].upcase}#{string[1…-1]}”}

I understand the output generated by this block but what confuses my is the last part: #{string[0].upcase}#{string[1…-1]} Can someone explain to me why the string array is passes it twice. what i see is string[0].upcase returns the first element in the array capitalized but then the string[1…-1] return the values in the array from the second value to the end… what am i missing. Keep it simple please.


#2

This a string with interpolation which permits writing an expression into the output.

"#{expression}#{expression}"

has no printable characters other than those resulting from the expressions.

string[0]

is the first index of the string.

#{string[0].upcase} converts the first letter to uppercase.

#{string[1..-1]} (notice only two dots) selects all letters from the second to the last in the string.

mystring becomes Mystring.


Aside

Please remember to include a link to the exact lesson when posting questions in the forums that relate to exercises. It makes it so much easier for us to zero in on the lesson without having to track down the unit and exercise.


#3

will do thanks, So if i am understanding you correctly, that “#{string[0].upcase}#{string[1…-1]}” is the same as calling a my_string.capitalize ?


#4

Yes, that is correct.

"#{string.capitalize}"

is the same as,

“#{string[0].upcase}#{string[1..-1]}”

#5

Awesome, I might be getting this stuff after all!


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.