From: Peter Vandenabeele Date: 2011-09-24T17:52:10+09:00 Subject: Re: Conditional statements with multiple arguments --001636920cf07c7afa04adac0a56 Content-Type: text/plain; charset=UTF-8 On Sat, Sep 24, 2011 at 4:53 AM, Thomas B. wrote: > Good afternoon everyone, > > I'm a beginner in Ruby with a little bit of experience programming in > Java and PHP. Right now I'm having a difficult time grasping conditional > (if/elsif) statements in Ruby. I'm trying to get an if statement to > evaluate two different strings...i.e. > > action = gets.chomp() > > if action == "M" || "m" > menu() > else > puts "Please enter in a valid selection." > end > > So, from what I'm used to in programming, the if action == "M" || "m"" > should evaluate to a conditional statement as to whether or not action > is equal to the strings "M" or "m". However, this does not seem to be > the case. It's not giving any kind of an error, however, it is calling > the menu() method regardless of what is entered. I can easily make this > work by separating the "M" and the "m" into an if and an elsif argument > i.e: > > action = gets.chomp() > > if action == "M" > menu() > > elsif action == "m" > menu() > > else > puts "Please enter in a valid selection." > end > > The above process does seem to work, however, isn't there a simpler way > of accomplishing this so I'm not adding unnecessary conditional > statements? I believe a nice way to achieve it could be the "case" statement. That does allow you to give a list of strings to match against. E.g. peterv@ASUS:~$ cat case.rb action = gets.chomp() case action when "M", "m" puts "Found 'M' or 'm'" else puts "Enter a valid selection" end peterv@ASUS:~$ ruby case.rb A Enter a valid selection peterv@ASUS:~$ ruby case.rb M Found 'M' or 'm' peterv@ASUS:~$ ruby case.rb m Found 'M' or 'm' peterv@ASUS:~$ Of course, you could also have said: if action.downcase == 'm' > I've been trying to find more resources online about > conditional statements with multiple arguments, but none of them have > seemed to help out. I'm guessing that my understanding of the || and > "or" statements is misguided. > The specific error in your original code your code => if action == "M" || "m" is that this will be interpreted as if (action == "M") || "m" and that a string "m" evaluates to true. So what you where saying is: if (action is "M") or true which will be always true. HTH, Peter --001636920cf07c7afa04adac0a56--