Reputation: 11
I am trying to create a do block with index. But I keep getting: syntax error, unexpected '|'
This is my code:
def same_char_collapse(str)
chars = str.split("")
while chars.each.with_index do | letter, i |
if letter[i] == letter[i + 1]
letter[i] = ""
letter[i +1] = ""
end
break
end
end
The error I am getting:
/tmp/file.rb:5: syntax error, unexpected '|'
...hile chars.each.with_index do | letter, i |
... ^
/tmp/file.rb:5: syntax error, unexpected '|', expecting '='
...ach.with_index do | letter, i |
... ^
What am I doing wrong?
Upvotes: 1
Views: 48
Reputation: 28285
This line doesn't make sense:
while chars.each.with_index do |letter, i|
I think you just meant to use:
chars.each.with_index do |letter, i|
A while loop, in any language, takes the form: while(conditional) ....
. You don't have a conditional here, so it's not a valid use case for while
.
On the other hand, methods such as each
will:
Call the given block once for each element in
self
, passing that element as a parameter.
Note: You also could have used chars.each_with_index
instead of .each.with_index
.
Upvotes: 2