Ruby ending if block [closed] - ruby

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I am a total beginner to Ruby. I am trying to print if an object is an array or an integer, but I am getting a syntax error I cannot figure how to solve it.
D:\Ruby>ruby -c Learning-Ruby\loops_stuff.rb
Learning-Ruby/loops_stuff.rb:9: syntax error, unexpected keyword_else, expecting keyword_end
Learning-Ruby/loops_stuff.rb:11: syntax error, unexpected end-of-input, expecting keyword_end
This is my code
obj = ["a", 1, 3.6]
if object.is_a(obj)
puts "Is array: "
obj.each do |index|
puts index
elseif object.is_i(obj)
puts "Is integer: {#obj}"
else
puts "Is neither array or integer"
end

the keyword is elsif (without the e in the middle)
obj = ["a", 1, 3.6]
if obj.is_a?(Array)
puts "Is array: "
obj.each do |index|
puts index
end
elsif obj.is_a?(Integer)
puts "Is integer: #{obj}"
else
puts "Is neither array or integer"
end
also stumbled over this in my first ruby sessions

For addition, you can use case..when statement (looks more elegant as for me):
case obj
when Integer
#some actions
when Array
#some actions
else
#some actions
end

According to the strings you print, this might be what you want to code.
obj = ["a", 1, 3.6]
if obj.is_a?(Array)
puts "Is array: "
obj.each do |index|
puts index
end
elsif obj.is_a?(Integer)
puts "Is integer: {#obj}"
else
puts "Is neither array or integer"
end
The output is:
Is array:
a
1
3.6

Related

ruby not equal operator doesn't work but equal does [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 2 years ago.
Improve this question
I'm very puzzled with this simple method I have where I'm just trying to puts a character of an array if, when compared with the character of another array, it is different.
This works with the == operator but not with the !=
Maybe it has to do with the each loops but I can't see what the error is. Any ideas?
Thanks
def remove_vowels(s)
nw_s = s.chars
vowels = "aeiou".chars
result = []
nw_s.each do |char|
vowels.each do |vowel|
if char != vowel
print char
end
end
end
end
remove_vowels("apple")
Nested each is no ruby way of doing this kind of task. You can write this
def remove_vowels(s)
nw_s = s.chars
vowels = "aeiou".chars
result = nw_s.map {|k| k unless vowels.include?(k) }.compact
end
remove_vowels("apple")
One line of code instead seven

Having trouble using the modulo operator with a method [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 7 years ago.
Improve this question
I have two methods turn_count(board) and current_player(board). The turn_count(board) method, which returns the number of "X"s and "O"s in an array is working appropriately. But the current_player(board) method, which is supposed to puts "X" if turn_count(board) is even and "O" if turn_count(board) is odd keeps giving me an error. The error is:
/Users/john/Desktop/test file.rb:13:in current_player': undefined method%' for nil:NilClass (NoMethodError)
from /Users/john/Desktop/test file.rb:18:in `'
Clearly it's saying there's an issue with the modulo operator being used, but i'm not sure why and have been wracking my brain trying to figure it out.
Any help is greatly appreciated!
def turn_count(board)
count = 0
board.each do |x| if x == "X" || x == "O"
count = count + 1
end
end
puts count
end
def current_player(board)
if turn_count(board) % == 0
puts "X"
else
puts "O"
end
end
The problem is you are using % on a NilClass. Your turn_count() method returns nil. Check what happens if you replace puts count with count.

Checking if content of an array is all integers [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm working on a sorting code. I would like to check if my array contains non integers. Here is my code:
array = Array.new
puts "Please enter your 3 digits."
3.times do
str = gets.chomp.to_i
array.push str.to_i
end
if array.is_a?(Numeric) == false
puts "Error, only use Integers please!"
else
print "Here are your sorted numbers: #{array.sort}"
end
You clearly can't gets.chomp.to_i (or the equivalent, gets.to_i), because that will only return integers. You therefore need to see if the string represents a number before adding it to the array.
You can do that with a regular expression or confirm that Kernel::Integer does not raise an exception (and catch it if it does).
A regular expression that would work is simply:
str =~ /^-?\d+$/
after
str = gets.chomp.strip
To use Kernel::Integer:
def integer?(str)
begin
Integer(str)
rescue ArgumentError
return false
end
str.to_i
end
For example,
integer?("-33") #=> -33
integer?("-x33") #=> false
integer?(" 33 ") #=> 33
integer?("33\n") #=> 33
The last two examples show that you can drop chomp.strip from gets.chomp.strip when using this approach.
If you wish to allow integers or floats, change the regular expression to:
/^-?\d+\.?\d*$/
or check to see that Kernel::Float raises an exception:
def float?(str)
begin
Float(str)
rescue ArgumentError
return false
end
str.to_f
end
float?("-33.4") #=> -33.4
float?("-33") #=> -33.0
float?("x33.4") #=> false
float?(" 33.4\n") #=> 33.4
With the code you have above your array is guaranteed to contain integers since you are converting your input to Integers using to_i:
array.push str.to_i
You are in fact doing it twice. When you read the string from STDIN and when you push it onto the array.
You need to check to see if the input is a string before you call to_i.
3.times do
str = gets.chomp
# code to verify if str is numeric.
array.push str
end
There are lots of ways to implement that code depending on what your requirements are. Integers only could be done like this:
unless str =~ /^\d+$/
puts "Error, only use Integers please!"
exit
end
The above would work for any positive integers, but not negative. It would also fail if you allowed decimals. But it gives you an idea. Search "ruby check if string is a number" and you'll find a lot more info.
Also note that the above fails as soon as it finds a non integer instead of waiting till after.

Ruby NameError: Undefined local variable [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Just started to go through the 7 languages in 7 weeks book; day one problem make a simple higher or lower game in ruby. When I execute my script I get the following error but I don't know why.
EDIT: This is thrown after I guess once.
NameError: undefined local variable or method actual' for main:Object
from guess_game.rb:2:inguess'
from guess_game.rb:22
def guess(guess, acutal)
unless guess == actual
if guess > actual
puts 'Lower'
else
puts 'Higher'
return false
end
end
puts 'Correct'
return true
end
answer = rand(10)
game_won = false
puts 'I am thinking of a number, what is it?'
until game_won
num = gets.to_i
# Static Debug Line
puts "Guess #{num} : Answer #{answer}"
game_won = guess(num, answer)
end
def guess(guess, actual)
unless guess == actual
if guess > actual
puts 'Lower'
else
puts 'Higher'
return false
end
end
puts 'Correct'
return true
end
Problem: Spelling mistake, Corrected

Add multiple puts in a block [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Whats the difference between this 2? why one works and the other does not?
array.each{ |item| puts "The item is #{item}" puts item + 1 }
array.each do |item|
puts "The item is #{item}"
puts item + 1
end
When you have two statements in a single line, you need to put a ; between the two. Thus: puts "The item is #{item}"; puts item + 1.
You're trying to cram two expressions where only one is expected. You can separate the two expressions using a semicolon:
array.each { |item| puts "The item is #{item}"; puts item + 1 }
Why not just supply both "The item is #{item}" and item + 1 to puts?
array.each { |item| puts "The item is #{item}", item + 1 }
array.each{ |item| puts "The item is #{item}" puts item + 1 }
This is simply a syntax error, as mentioned by your interpreter:
syntax error, unexpected tIDENTIFIER, expecting '}'
Your second example is syntactically correct and so does not raise an error.
array.each do |item|
puts "The item is #{item}"
puts item + 1
end
You are missing a space after the each method call, before the first { which is perhaps at best a bad habit.
Also, you can have your first example as:
array.each {|item| puts "The item is #{item}"
puts item + 1 }
And it would become syntactically correct, because of the new line. Nothing says that the curly brace form of a block given to each has to be written on one line, though it is one common convention.
For style, though, (and this is not Code Review, I know), I would probably try to keep the code consistent.
array.each do |item|
puts "The item is #{item}\n#{item.next}"
end
Or perhaps with the curly braces:
array.each do { |item| puts "The item is #{item}\n#{item.next}" }

Resources