Ruby unexpected |, expecting = - ruby

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?

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.

Related

Unexpected keyword_end error, yet syntax seems fine

This function is supposed to pull names from a Comma Separated Values file, and place them into an array.
def xprt_csv_to_ary(csv_file)
namecatcher_regex = "/^[\.{1}]([A-Z]+)\.{3}/" # Matches up to char before next name
current_word = 0
names_array = []
while current_word < 5000
if current_word == 0
name = csv_file.readline.match(namecatched_regex)
else
name = csv_file.past_match.match(namecatcher_regex)
end
names_array[current_word] = name
current_word ++
end
return names_array
end
I'm getting the following error:
syntax error, unexpected keyword_end
I would be as happy to be referred to an existing question that solves my problem as to have someone answer me directly.
Your error comes from line:
current_word ++
There's no such syntax in Ruby. It should be:
current_word += 1
What's more, you create your regexp incorrectly. It should be:
namecatcher_regex = /^[\.{1}]([A-Z]+)\.{3}/
There may be some other errors that I didn't notice.
On this line:
current_word ++
You are telling Ruby to add something to current_word, but you never tell it what to add, instead there's an end directly on the next line. You are missing the operand to the unary +. It should be something like
current_word + something_else
or
current_word + +something_else
In Ruby, whitespace is allowed around operators, so
a +
b
# equivalent to a + b, which is equivalent to a.+(b)
and even
+
a
# equivalent to +a, which is equivalent to a.+#()
is perfectly fine, so if you combine the two, you get that
a + +
b
# equivalent to a + +b, which is equivalent to a.+(b.+#())
is also perfectly fine, and since whitespace around operands is perfectly fine but optional,
a+b
and
a ++
b
# equivalent to a + +b as above
is also perfectly fine.
That's why you only get the error on the next line with the end, because only there can Ruby tell that you are missing the operand to the unary prefix + operator.

Noob and receiving syntax error for google-search code

Pretty much have typed code from this example word for word, and receiving following syntax error message. Please help!!
https://github.com/visionmedia/google-search/blob/master/examples/web.rb
My code:
require "rubygems"
require "google-search"
def find_item uri, query
search = Google::Search::Web.new do |search|
search.query = query
search.size = :large
search.each_response {print "."; #stdout.flush}
end
search.find {|item| item.uri =~ uri}
end
def rank_for query
print "%35s " % query
if item = find_item(/vision\-media\.ca/, query)
puts " #%d" % (item.index +1)
else
puts " Not found"
end
end
rank_for "Victoria Web Training"
rank_for "Victoria Web School"
rank_for "Victoria Web Design"
rank_for "Victoria Drupal"
rank_for "Victoria Drupal Development"
Error message:
Ruby Google Search:9: syntax error, unexpected keyword_end, expecting '}'
Ruby Google Search:11: syntax error, unexpected keyword_end, expecting '}'
Ruby Google Search:26: syntax error, unexpected $end, expecting '}'
You've inadvertently commented out the remainder of line 9:
search.each_response {print "."}
Note that the # character in Ruby denotes a comment; i.e., everything on the same line to the right of the # inclusive is considered comment and is not compiled as Ruby code.
print 'this ' + 'is ' + 'compiled'
#=> this is compiled
print 'this' # + 'is' + 'not'
#=> this
Note that the bracket {} notation encapsulates a single executable line contained within a block. What you're trying to do, however, is to execute two commands. For this, it may be more semantically readable to use Ruby's block notation:
search.each_response do
print '.'
STDOUT.flush
end
Instead of #stdout.flush, type $stdout.flush.
The last line of the do block in find_item is:
search.each_response {print "."; #stdout.flush}
Where the # in Ruby marks the beginning of comment. You've commented out the remainder of the line, but not before opening a bracket {. The lack of it being closed is the source of your error.
In order for your code to be correct, you should change the # to $ to access the global stdout object.

How can I logically OR two include? conditions in Ruby?

I am starting learn Ruby, need some help with the include? method.
The below code works just fine:
x = 'ab.c'
if x.include? "."
puts 'hello'
else
puts 'no'
end
But when I code it this way:
x = 'ab.c'
y = 'xyz'
if x.include? "." || y.include? "."
puts 'hello'
else
puts 'no'
end
If gives me error when I run it:
test.rb:3: syntax error, unexpected tSTRING_BEG, expecting keyword_then or ';' o
r '\n'
if x.include? "." || y.include? "."
^
test.rb:5: syntax error, unexpected keyword_else, expecting end-of-input
Is this because the include? method cannot have handle logic operator?
Thanks
The other answer and comment are correct, you just need to include parenthesis around your argument due to Ruby's language parsing rules, e.g.,
if x.include?(".") || y.include?(".")
You could also just structure your conditional like this, which would scale more easily as you add more arrays to search:
if [x, y].any? {|array| array.include? "." }
puts 'hello'
else
puts 'no'
end
See Enumerable#any? for more details.
It's because of Ruby parser, it can't recognize the difference between the passing an arguments and logical operators.
Just modify your code a little bit to distinguish the arguments and operator for Ruby parser.
if x.include?(".") || y.include?(".")
puts 'hello'
else
puts 'no'
end

Adding things inside while loop causes syntax error

I'm trying to read and process lines from a file in Ruby.
I have a while loop that reads each line. If the all the while loop does is split the lines, it works fine. When I add a regex matching clause, I get a syntax error, unexpected kEND
and syntax error, unexpected $end, expecting kEND
Specifically, here is the code which "compiles"
def validate
invalid = 0
f = File.open(ARGV[0], "r")
while (line = f.gets)
vals = line.split(",")
end
end
if (ARGV[1] == "validate")
validate
end
while this code
def validate
invalid = 0
f = File.open(ARGV[0], "r")
while (line = f.gets)
vals = line.split(",")
match0 = Regexp.new(/0-9]{1,4}/)
unless (match0.match(vals[0]))
invalid ++
end
end
end
if (ARGV[1] == "validate")
validate
end
throws the error
schedule.rb:10: syntax error, unexpected kEND
schedule.rb:18: syntax error, unexpected $end, expecting kEND
The syntax error is not due to the regex. It's due to the "++". Ruby doesn't have the "++" operator. Instead, you should use:
invalid += 1
Besides, there is a bracket missing in your regexp (character class).
/0-9]{1,4}/
It should read
/[0-9]{1,4}/
There is no C-style increment/decrement operator. Instead use
invalid = invalid + 1
or
invalid += 1

Syntax error, unexpected '='

I have the following as part of a class
def to_s
i = 0
first_line? = true
output = ''
#selections.each do | selection |
i += 1
if first_line?
output << selection.to_s(first_line?)
first_line? = false
else
output << selection.to_s
end
if i >= 5
output << "\r"
i = 0
else (output << " $ ")
end
end
return output
end
And i am getting the following syntax errors
SyntaxError: list2sel.rb:45: syntax error, unexpected '='
first_line? = true
^
list2sel.rb:47: syntax error, unexpected keyword_do_block, expecting keyword_end
#selections.each do | selection |
^
list2sel.rb:51: syntax error, unexpected '='
first_line? = false
^
What give, also thanks in advance, this is driving me nuts.
I suppose, you can't name variables with '?' at the end.
Variable names (with a few exceptions noted below) can only contain letters, numbers and the underscore. (Also, they must begin with a letter or the underscore; they can't begin with a number.) You can't use ? or ! in a variable name.
Beyond that rule, there is a strong convention in Ruby that a question mark at the end of something indicates a method that returns a boolean value:
4.nil? # => returns false....
So even if you could use it, a variable like first_line? would confuse (and then annoy) the hell out of Rubyists. They would expect it be a method testing whether something was the first line of something (whatever exactly that means in context).
Exceptions about variable names:
Global variables begin with $ - e.g., $stdin for standard input.
Instance variables begin with # - e.g. #name for an object
Class variables begin with ## - e.g. ##total for a class
I believe this is a more concise way of doing the above (untested):
def to_s
output = ""
#selections.each_with_index do | selection,line |
output << line==0 ? selection.to_s(true) and next : selection.to_s
output << line % 5 ? " $ " : "\r"
end
return output
end
If you are not a fan of the ternary operator (x ? y : z) then you can make them ifs:
def to_s
output = ""
#selections.each_with_index do | selection,line |
if line==0
output << selection.to_s(true)
else
output << selection.to_s
if line % 5
output << " $ "
else
output << "\r"
end
end
end
return output
end
Variable names allow non-ASCII letters, and there are non-ASCII versions of the question mark, so you can put question marks (and also some forms of space characters) into variable names.

Resources