Ruby/Language Basics/Boolean Operators
Материал из Wiki.crossplatform.ru
Версия от 17:10, 26 мая 2010; (Обсуждение)
And, or and Not
iAmChris = true iAmPurple = false iLikeFood = true iEatRocks = false puts (iAmChris and iLikeFood) puts (iLikeFood and iEatRocks) puts (iAmPurple and iLikeFood) puts (iAmPurple and iEatRocks) puts puts (iAmChris or iLikeFood) puts (iLikeFood or iEatRocks) puts (iAmPurple or iLikeFood) puts (iAmPurple or iEatRocks) puts puts (not iAmPurple) puts (not iAmChris ) # true # false # false # false # true # true # true # false # true # false
Are more than two statements OK?
a = b = c = d = 2 if a == 10 || b == 27 || c = 43 || d = -14 print sum = a + b + c + d end
Chaining together multiple comparisons is also possible with a clever use of parentheses:
age = 24 gender = "male" puts "You"re a working age man" if gender == "male" && (age >= 18 && age <= 65)
check whether one or the other is true by using ||
age = 24 puts "You"re either very young or very old" if age > 80 || age < 10
have more than two statements separated by &&
a = 1 b = 2 c = 3 d = 4 if a == 10 && b == 27 && c == 43 && d == -14 print sum = a + b + c + d end
|| operator is or.
# When you use || or or, if any of the statements are true, the code executes: ruby = "nifty" programming = "fun" if ruby == "nifty" or programming == "fun" puts "or!" end
the && operator means "and."
ruby = "nifty" programming = "fun" if ruby == "nifty" && programming == "fun" puts "and" end
Use or in if statement
puts "Hello, what\"s your name?" name = gets.chomp puts "Hello, " + name + "." if (name == "Chris" or name == "Katy") puts "What a lovely name!" end
use the keyword and instead of &&.
ruby = "nifty" programming = "fun" if ruby == "nifty" and programming == "fun" puts " and and" end