IF - multiple conditions allowed?

Hey all!

Wow, long time no post… good to see the list is still here (because
I’m stuck) ;}

In a text based game I’m writing to practice my Ruby via, I have the
option for a player to Attack or Flee. However, I’d like them to be able
to type Attack or just a.

I have this kind of thing working for a CASE statement, but I can’t get
the same logic working for an IF statement if my Hero’s life depended on
it…

WORKS:

case action
when “quit”, “q”
game_quit #(ad-method-lib)

CODE IN THE IF:

if combat_action == “flee”
flee #(ad-method-lib)

elsif combat_action == “attack”
puts “\n…you attack\n”

WHAT I IMAGINE IT WOULD BE LIKE

if combat_action == “flee” OR “f”
flee #(ad-method-lib)

OR MAYBE IT’S

elsif combat_action == “attack”, “a”
puts “\n…you attack\n”

…or not


Is there a way to add multiple conditions like this to IF statements?
More elsif? (Seems very repetitive).

Thanks as always,

(File attached)

DE

You need to be explicit when you’re comparing your answer.
When you write:
if combat_action == “flee” or “f”
Then it will always be true, because “f” is a string, and strings are
truthy.

Instead you could write:
if combat_action == “flee” or combat_action == “f”

Or maybe:
if [“flee”, “f”].include? combat_action

Or:
if combat_action =~ /\A(flee|f)\z/

You could always reverse the logic of “include?” if you wanted it to
flow left to right as well:

irb(main):001:0> class Object
irb(main):002:1> def in? array
irb(main):003:2> array.include? self
irb(main):004:2> end
irb(main):005:1> end
=> nil
irb(main):006:0> combat_action = “f”
=> “f”
irb(main):007:0> combat_action.in? [“flee”, “f”]
=> true
irb(main):008:0> combat_action.in? [“attach”, “a”]
=> false

Excellent, thanks Joel!

I would never have thought of that. If I’m reading this correctly, it’s
essentially having an array and seeing if the contents evaluate to true?

(ref: Class: Array (Ruby 1.9.3))

Tried them all out but have gone with the below as it reads better in my
head.


if [“flee”, “f”].include? combat_action
flee #(ad-method-lib)

elsif [“attack”,“a”].include? combat_action


Onwards in the adventure!

DE

If you were using an object with those methods defined, you could also
use #respond_to?, meaning you could eliminate all the different options
and
stick with one:

Here’s a simple example:

class Adventure
def flee
puts ‘flee code’
end
alias f flee
def attack
puts ‘attack code’
end
alias a attack
def quit
puts ‘press enter to quit…’
gets
exit
end
alias q quit
end

my_adventure = Adventure.new

loop do

puts ‘Enter a command…’
input = gets.chomp
if my_adventure.respond_to? input
my_adventure.send input
else
puts “Invalid command: #{ input }”
end

end