problem with if and else code... in ruby - ruby

Do not treat to the variables and conditions ...
def index
end
def search
count = 1
while count < 3
if count == 1
#movie = "not found" if #code1 == nil || #code1 == ""
if #movie == ""
end
end
if count == 2
#movie = "not found" if #code1 == nil || #code1 == ""
if #movie == ""
if #code1.include? "movshare"
end
if #code1.include? "novamove"
end
end
end
count++
end
end
end
what is the problem in this code? i get an error:
syntax error, unexpected keyword_end

you have one more unnecessary 'end'. There are 9 opening clauses including def, while and if and 10 closing end

You are confusing the interpreter with your count++. ++ does not exist in Ruby. You need to use count += 1. The interpreter is probably assuming that is an expression involving addition, and expecting another operand but instead finding end

Related

Why am I getting "not a number" error in this code? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I'm just hoping someone might be able to help me out with this code:
def write(aFile, number)
index = 1
while (index < number)
aFile.puts(index.to_s)
index += 1
end
end
def read(aFile)
count = aFile.gets
if (is_numeric?(count))
count = count.to_i
else
count = 0
puts "Error: first line of file is not a number"
end
index = 0
while (count < index)
line = aFile.gets
puts "Line read: " + line
end
end
# Write data to a file then read it in and print it out
def main
aFile = File.new("mydata.txt", "w")
if aFile
write(aFile, 11)
aFile.close
else
puts "Unable to open file to write!"
end
aFile = File.new("mydata.txt", "r")
if aFile
read(aFile)
aFile.close
else
puts "Unable to open file to read!"
end
end
# returns true if a string contains only digits
def is_numeric?(obj)
if /[^0-9]/.match(obj) == nil
true
end
false
end
main
The result I'm trying to get is this:
Line read: 0
Line read: 1
...
Line read: 10
But I'm getting:
Error: first line of file is not a number
Why is this the case? Something must be wrong with my code.
def is_numeric?(obj)
if /[^0-9]/.match(obj) == nil
true
end
false
end
Result of a code block (such as method body) is the last expression evaluated in it. Your true becomes the value of the if and is ignored, because the next expression evaluated is false, which is what is always returned. There are several ways you can improve this.
def is_numeric?(obj)
return true if /[^0-9]/.match(obj).nil?
false
end
def is_numeric?(obj)
/[^0-9]/.match(obj).nil?
end
def is_numeric?(obj)
/[^0-9]/ !~ obj
end
def is_numeric?(obj)
Integer(obj) rescue false
end
And many more.

Read and Write Ruby

Can't seem to get my data to be read as an integer and print out the data, instead gets the 2nd option which is Error: first line of file is not a number.
def write(aFile, number)
aFile.puts(number)
index = 0
while (index < number)
aFile.puts(index)
index += 1
end
end
def read(aFile)
count = aFile.gets
if (is_numeric?(count))
count = count.to_i
else
count = 0
puts "Error: first line of file is not a number"
end
index = 0
while (count < index)
line = aFile.gets
puts "Line read: " + line
index += 1
end
end
def main
aFile = File.new("mydata.txt", "w") # open for writing
if aFile # if nil this test will be false
write(aFile, 10)
aFile.close
aFile = File.new("mydata.txt", "r")
read(aFile)
aFile.close
else
puts "Unable to open file to write or read!"
end
end
def is_numeric?(obj)
if /[^0-9]/.match(obj) == nil
true
end
false
end
main
Any help on how to fix this would be great.
Your problem is a lack of return
def is_numeric?(obj)
if /[^0-9]/.match(obj) == nil
true
end
false
end
This function ALWAYS returns false. There is no case where it ever returns true. Ruby functions always return at an explicit return() and if none is called, then the last line is returned. That means the true you have there does nothing. It's simply thrown away and false is returned.
A simplified form of this existing function is just:
def is_numeric?(obj)
false
end
To fix this problem, you need to return when it’s true:
def is_numeric?(obj)
if /[^0-9]/.match(obj) == nil
return(true)
end
false
end
You can also simplify this to:
def is_numeric?(obj)
/[^0-9]/.match(obj).nil?
end
Also, if you’re using Ruby 2.4+, a more efficient way to do this would be to use the match? method and a negation. match sets up some handy MatchData (and backreferences), but since you if you don't need any of that, you can save the overhead by using match?, which simply returns a boolean.
def is_numeric?(obj)
!/[^0-9]/.match?(obj)
end
Another problem is your logic of count < index.
while (count < index)
line = aFile.gets
puts "Line read: " + line
index += 1
end
Since index is 0, the only time count will be less than index, is if count is less than 0. Perhaps you meant while (count > index)?
Notes:
https://www.ruby-lang.org/en/news/2016/12/25/ruby-2-4-0-released/

Ruby - How to Execute something and then Break inside IF block?

EDIT: Someone pointed out that I needed to break correctly so I am editing the question
Scenario:
Please see following code:
print "UserID: "
uid = $stdin.gets.chomp
print "Password: "
pwd = $stdin.gets.chomp
usr_inp = "#{uid};#{pwd}"
login_status = -1
# login_info.txt - "#{userid};#{password}" - format
File.open(File.join(File.dirname(__FILE__), 'login_info.txt'), "r") do |f|
f.each_line do |line|
puts line
if (line.chomp == usr_inp)
login_status = 1
elsif (line.chomp != usr_inp && line.include?(uid)) #case a person inputs invalid password
login_status = 0
elsif (line.chomp != usr_inp && !(line.include?(uid))) #case a person inputs an invalid id
login_status = 2
end
end
end
if (login_status == 1)
puts "\nLogged in successfully: #{uid}"
elsif (login_status == 2)
puts "\nSorry, that Employee does not exist."
elsif (login_status == 0)
puts "\nLogin failed.\nPlease check credentials."
end
Problem:
break if (condition) exists in Ruby. But I don't waht that.
I want to do something like:
if (condition x)
(do something)
break
elsif (condition y)
(do something else)
break
else
(whatever)
end
Maybe I am not understanding how ruby code works. Whenever I try to put the break as I want to use it, it associates with the next elsif.
Please help.
It depends on what you need and where you need it.
A script like this:
condition = 1
case condition
when 1
puts 'one'
break
when 2
puts 'two'
else
puts 'Other %s' % condition
end
puts 'end'
has a syntax error. break leaves a loop and there is no loop.
But with a loop, this works:
[1,2,3].each{|condition|
case condition
when 1
puts 'one'
break
when 2
puts 'two'
else
puts 'Other %s' % condition
end
puts 'end'
}
puts 'very end'
The output is:
one
very end
You see, the loop is stopped.
If you want to continue the loop with the next element, you need next (sorry, I'm just not aware what break is doing really in Java - it's been a long time since my last Java program):
[1,2,3].each{|condition|
case condition
when 1
puts 'one'
next
when 2
puts 'two'
else
puts 'Other %s' % condition
end
puts 'end %s' % condition
}
puts 'very end'
The result:
one
two
end 2
Other 3
end 3
very end
When you are not inside a loop (like in your code snippet), you may use exit (leave the program) or return (leave a method).

Getting an "unexpected keyword_end" for if/else statements

def load x
#maze_string = x
#maze_string_split = x.chars.to_a
string_counter = 0
y=#height
x=#width
(0..(y*2+1)).each do |n|
if #maze_string_split[counter] !=1
puts "Error in given string, wall expected"
else
#maze_array[n] = #maze_string_split[counter]
counter++
end
(0..(x*2)).each do |m|
if n==0 || n==(y*2+1) || m==(x*2)
if #maze_string_split[counter] != 1
puts "Error in given string"
else
#maze_array[n][m] = #maze_string_split[counter]
counter++
end
else
#maze_array[n][m] = #maze_string_split[counter]
counter++
end
end
end
end
I am getting the error in the title on the "end" statements at the conclusion of each if/else block. All seems well, but the errors remain. I tried looking to see if anyone else had this problem, but I can't find anything specific to my problem
Ruby does not have a ++ or -- operator.
Ruby will not parse these out correctly in that is the reason you're getting an unexpected keyword_end, it is expecting another operand.
Replace the
counter++ with counter += 1
Also, note that your variable is not called counter but string_counter

Ruby: passing array items into a case statement

I am attempting to pass an array into a case statement so I can read the array elements as commands. Unfortunately, it seems that it is not working and the program jumps to the else statement.
def input_console()
quit = 0
puts "Tell me what you want to do:"
loop do
print "\n >>> "
input = gets.chomp
sentence = input.split
case sentence
when sentence[0] == "go" && sentence[1] == "to"
puts sentence[2]
when sentence[0] == "quit"
quit = 1
else
puts "No le entiendo Senor..."
end
break if quit == 1
end
end
This piece of code returns "No le entiendo Senor..." whatever you introduce. I expected to get the place I want to go after stating "go to Wherever".
Please, ¿may you help me?
You can do this by making your case statement independent of a specific variable.
change
case sentence
to
case
Here is an example of how you would use case-when while checking for values in the array.
numbers = [1,2,3]
case
when a[1] == 2
p "two"
else
p "nothing"
end
So in your case you can just say
case
when sentence[0] == "go" && sentence[1] == "to"
puts sentence[2]
when sentence[0] == "quit"
quit = 1
else
puts "No le entiendo Senor..."
end
Why are you making this a case statement? (And why is quit a Fixnum rather than a boolean? Actually, why have it at all?)
while true
# ... prompt and get input ...
if sentence[0] == "go" && sentence[1] == "to"
puts sentence[2]
elsif sentence[0] == "quit"
break
else
puts "No le entiendo Senor..."
end
end
You could use regular expressions. Something like this:
case gets
when /\Ago to (.*)\Z/
puts $1
when /\Aquit\Z/
# handle quit
else
puts "No le entiendo Senor..."
end
\A matches the beginning of string and \Z matches just before the trailing newline, so you don't need chomp.

Resources