Block Syntax


#1

Can someone explain each expression and how they work together as a whole?

Input:

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

Output:

Ryan
Jane

Here is my thought process:

-There is an array with string literals “ryan” and “jane” contained
-.each indicates that each string literal within the array will be targeted
-|string| is the element alias that the each string literal takes on
-(?) puts “#{string[0].upcase}” capitalizes the 0th index per string literal (“R” and “S”)
-(?) #{string[1…-1]} Why are “1…-1” used for the arguments?


#2

Array.each takes a block, so,

Array.each { |block_parameter| # code }

or,

Array.each do |block_parameter|
    # code
end

When curly braces are used inside a string they are special blocks, on string interpolation methods.

puts "This output contains an interpolated value, #{expression}."

expression can be any expression that returns a value.


#3

Thanks for the reply,

Why are “1…-1” used for the arguments for #{string[1…-1]}?


#4

Looking at the docs, Range we see that ... means exclude the last value in the range…

string[1...-1]

will actually skip the last letter and only print,

Rya
Jan

Using .. (two dots) includes the last value, so,

string[1..-1]

will output

Ryan
Jane

when the complete expression above is used. -1 is the rightmost index of the string.


#5

I appreciate the help!

Is

string[1…-1]

the more typically used notation when you want to return the entire string?

Also, I’m not sure why, but whenever I submit 2 dots, it comes out as 3 dots


#6

The editor is interpreting ‘…’ as a horizontal ellipses . Post inline code with a single back tick wrapper, and blocks of code with three back tick wrapper.

This is `inline code`.
```
# This is block code.
```
string[1..-1]

is what is known as a slice, starting at the second character and continuing to the last.


#7

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