From: "David A. Black" Date: 2008-05-02T23:13:52+09:00 Subject: Re: | versus || Any reason for this issue? --1926193751-363108668-1209737631=:16924 Content-Type: MULTIPART/MIXED; BOUNDARY="1926193751-363108668-1209737631=:16924" This message is in MIME format. The first part should be readable text, while the remaining parts are likely unreadable without MIME-aware tools. --1926193751-363108668-1209737631=:16924 Content-Type: TEXT/PLAIN; charset=X-UNKNOWN; format=flowed Content-Transfer-Encoding: QUOTED-PRINTABLE Hi -- On Fri, 2 May 2008, I=C3=B1aki Baz Castillo wrote: > Hi, why in the second case the non declared "my_var" variable is > processed but not in the first case? > > irb> nil || 2 || my_var > =3D> 2 > > irb> nil | 2 | my_var > NameError: undefined local variable or method `my_var' > > > Of course, I prefer the first case: 2 is already true so there is no > reason to read the next "my_var". Also, it's not good for performance, > is it? The single bar and the double bar are not related. | is a method that any class or object can define. For example, Fixnums use it as a bitwise operator: 4 | 1 # 5 (i.e., 100 | 001 =3D=3D 101) The single bar doesn't short circuit, whereas the || operator does. nil || 2 || 1/0 # 2 (it never reaches 1/0 so doesn't blow up) If you do nil || my_var, my_var will be reached and will give you an error if it isn't defined. David --=20 Rails training from David A. Black and Ruby Power and Light: INTRO TO RAILS June 9-12 Berlin ADVANCING WITH RAILS June 16-19 Berlin INTRO TO RAILS June 24-27 London (Skills Matter) See http://www.rubypal.com for details and updates! --1926193751-363108668-1209737631=:16924-- --1926193751-363108668-1209737631=:16924--