This page is READ-ONLY. It is generated from the old site.
All timestamps are relative to 2013 (when this page is generated).
If you are looking for TeX support, please go to

Ruby && and tip

this is a simple tip
Added by ruby 11 months ago  »  Votes: 2/2

The following code comes from Puppet source (lib/puppet/type/cron.rb)

1   # Verify that a number is within the specified limits.  Return the
2   # number if it is, or false if it is not.
3   def limitcheck(num, lower, upper)
4     (num >= lower and num <= upper) && num
5   end

Take a look at the comments, and the last statement (&&num). The operator && is not used as a condition check. It is to return the value if the previous checks are passed: If the num is out-of-range, the whole statement returns false. Otherwise, the last value num is returned. This is also how the operator && works :)

The code can be rewritten as

1   def limitcheck(num, lower, upper)
2     if (num >= lower and num <= upper)
3       return num
4     else
5       return false
6     end
7   end

But it is too long, isn't it?


Added by ruby 9 months ago

In Ruby, && and and has the same meaning. In PHP, && has higher priority than and. Forgetting this difference may cause some troubles

1 $a = $b && $c;   # equivalent to $a = ($b && $c);
2 $x = $y and $z;  # equivalent to `($x = $y) and $z`, or `$y and $z`