Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 629 Vote(s) - 3.49 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Checking if a variable is not nil and not zero in ruby

#1
I am using the following code to check if a variable is not nil and not zero

if(discount != nil && discount != 0)
...
end

Is there a better way to do this?
Reply

#2
You could initialize discount to 0 as long as your code is guaranteed not to try and use it before it is initialized. That would remove one check I suppose, I can't think of anything else.
Reply

#3
You could do this:

if (!discount.nil? && !discount.zero?)

The order is important here, because if `discount` is `nil`, then it will not have a `zero?` method. Ruby's short-circuit evaluation should prevent it from trying to evaluate `discount.zero?`, however, if `discount` is `nil`.
Reply

#4
<pre><code>
unless [nil, 0].include?(discount)
# ...
end
<code></pre>
Reply

#5
class Object
def nil_zero?
self.nil? || self == 0
end
end

# which lets you do
nil.nil_zero? # returns true
0.nil_zero? # returns true
1.nil_zero? # returns false
"a".nil_zero? # returns false

unless discount.nil_zero?
# do stuff...
end

Beware of the usual disclaimers... great power/responsibility, monkey patching leading to the dark side etc.
Reply

#6
if (discount||0) != 0
#...
end
Reply

#7
I believe the following is good enough for ruby code. I don't think I could write a unit test that shows any difference between this and the original.

if discount != 0
end
Reply

#8
if discount and discount != 0
..
end

update, it will `false` for `discount = false`
Reply

#9
<pre><code>
unless discount.nil? || discount == 0
# ...
end
<code></pre>
Reply

#10
You can convert your empty row to integer value and check zero?.

"".to_i.zero? => true
nil.to_i.zero? => true
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through