#party.chomp = gets # err. undefined var or method party #puts party
#party1 = gets # #party.chomp = party1 # err. undefined var or method party #puts party, party1
if party != nil
democrats.each { |i| print i, " "} if party == "democrats"
puts 'x5'
republicans.each { |i| print i, " "} if party == "republicans"
puts 'x6'
print "All presidents since 1976 were either Democrats or
Republicans\n"\
if (party != "democrats" && party != "republicans")
end
gets gives you a string or nil at EOF
I would not rely on EOF (<Ctrl>D) for interactive input but the choice
is yours of course, two approaches seem reasonable at first sight
puts "Enter democrats or republicans or any for party = or just <CR>"
unless party.empty?
case party
when "democrats"....
puts( democrats.join(" ") << 'x5' )
end
or
puts "Enter democrats or republicans or any for party = or just <Ctrl>D"
case party
when "democrats"
...
when nil
whatever
end
when i enter nil for gets, it is not comparing with another string
having nil value.
How did you enter nil for gets?
tried gets.chomp which also gives the same problem.
any help?
#party = gets.chomp # nil fails
if party != nil
democrats.each { |i| print i, " "} if party == "democrats"
puts 'x5'
republicans.each { |i| print i, " "} if party == "republicans"
puts 'x6'
print "All presidents since 1976 were either Democrats or
Republicans\n"\
if (party != "democrats" && party != "republicans")
end
if input == some_var
puts "The user entered the ruby nil object."
else
puts "The user didn't enter the ruby nil object."
end
--output:--
The user didn't enter the ruby nil object.
some_var = 'nil'
if input == some_var
puts "The user entered a string containing the characters n, i, and
l."
else
puts "The user didn't enter a string containing the charcters n, i,
and l."end
--output:--
The user entered a string containing the characters n, i, and l.
democrats.each { |i| print i, " "} if party == "democrats"
puts 'x5'
republicans.each { |i| print i, " "} if party == "republicans"
puts 'x6'
print "All presidents since 1976 were either Democrats or
Republicans\n"\
if (party != "democrats" && party != "republicans")
end
By the way, constructs like the above require that ruby evaluate all
three of the conditionals, where with a construct like:
if party == 'democrats'
puts 'dems'
elsif party == 'republicans'
puts 'rep'
else
puts "All presidents..."
end
as soon as one if-conditional is found to be true, the others below it
are not evaluated. Also notice that no complex conditional has to be
used for the else clause.
The ruby syntax where an if conditional comes at the end of a statement
is a particularly horrid one. I suggest you avoid it completely.