Adding things inside while loop causes syntax error - ruby

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

Related

Ruby unexpected |, expecting =

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.

syntax error, unexpected keyword_else, expecting ':' - RUBY

prompt("Welcome to Calculator! Enter your name:")
name = ''
loop do
name = Kernel.gets().chomp()
if name.empty()?
prompt("Make sure to use a valid name")
else
break
end
end
Not sure what I'm missing here.
I got this error messsage:
syntax error, unexpected keyword_else, expecting ':'
Try out
if name.empty?
Note that you can call methods that have no params without parentheses. Otherwise you should do name.empty?() because ? is part of the name of the method.
Anyway, your mistake is the ? after the if condition. The error message is saying you that with that ? it's trying to process a ternary operator that has this syntax
condition ? expression1 : expression2
for this reason it expects :
Line
if name.empty()?
is interpreted as ternary 'if' operator inside regular if statement:
if (name.empty() ? do_somethig : do_something_else )
and double dot is missing in your code
maybe you meant this:
if name.empty? # is equal to
if name.empty?()
Because question mark is a part of method name

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.

Converting between bases in Ruby

I'm trying to learn Ruby using problems from this subreddit. I'm working on a problem that's asking me to take a string containing a series of hex values separated by spaces, then convert them to binary and do some work based on the binary values. I have what looks like should be a working solution, but I'm getting errors when I run it. Here's the code:
print "enter: "
vals = gets.chomp.split
for i in 0...vals.length do
vals[i].hex.to_s(2)!
end
vals.each {|x| puts x}
I'm getting the following error messages:
test.rb:6: syntax error, unexpected '!', expecting keyword_end
test.rb:9: syntax error, unexpected end-of-input, expecting keyword_end
From what I understand, the .hex method should return the decimal value of a hex string, and to_s(2)! should convert that integer to a binary string. Obviously, though, I'm not getting something.
The bang after to_s is not a valid syntax on ruby. What you can have is a method ending with !, for example, chomp!. And there is no .to_s! method.
What you are looking for can be achieved by the following code:
print "enter: "
vals = gets.chomp.split
for i in 0...vals.length do
vals[i] = vals[i].hex.to_s(2)
end
vals.each {|x| puts x}

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.

Resources