From: Hal Fulton Date: 2003-09-03T13:54:45+09:00 Subject: Re: Possible to make compound if statements... Kurt Euler wrote: > Thanks Hal. Question: What do you mean by use ||? Could you > give an example? (I'm new to Ruby and programming.) || is essentially the same as or && is essentially the same as and So: if this == that || this =~ /another/ is the same as if this == that or this =~ /another/ History lesson: 'and' and 'or' and 'not' are used in languages like BASIC, Algol, and Pascal. && and || and ! are used in languages like C, C++, and Java. Ruby happens to know both forms. And by the way, don't confuse the &&/|| operators with the &/| operators. The latter are "bitwise" -- they act on individual bits in a number. For example. 5 | 6 is 7, since you're doing a bitwise OR of binary 101 and 110, giving binary 111. Whirlwind tour of truth and falsehood in Ruby: Two rules - 1. false and nil test as false 2. everything else tests as true Example: if this # prints "no" if this is nil or false; puts "yes" # prints "yes" if it's 0 or "" or [] else # or 237 or "foobar" or [1,2,3] or puts "no" # any other value imaginable. end Also remember that these expressions are "short-circuited" -- as soon as we know the result, we stop executing. Especially remember this if you're calling a method with side effects (in other words -- don't). Example: x = true || foo() # foo doesn't get called -- we already # know the result is true x = true && foo() # foo gets called -- it's necessary in # order to get the correct answer x = false || foo() # foo is called x = false && foo() # foo is not called This makes an interesting idiom possible. Suppose we want to assign 5 to x, but ONLY if it doesn't already have a value. An unassigned variable effectively has a value of nil. So we can say x = x || 5 to do this. Or using the shorthand that Ruby borrowed from C, we can say: x ||= 5 It's worth mentioning that this is a little strange on second thought, but makes sense on third thought. Variables in Ruby aren't declared. Ruby knows something is a variable when it sees an assignment to it. Now in the statement x = x || 5 you would take it for granted that the right hand side is evaluated first so that we can assign to the variable on the left hand side. But how can x || 5 make sense when x is undefined??? How does it even know x is a variable? The answer is that the interpreter "sees" the assignment to x at parse time and realizes that x is a variable. But since it has never been assigned, it will have the value nil. So the right hand side evaluates to nil || 5 (which is just 5). So then x gets its first "real" value. Confused yet?? Ask all the questions you want, we'll take turns on them. Cheers, Hal