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

#11
You can take advantage of the `NilClass` provided `#to_i` method, which will return zero for `nil` values:

unless discount.to_i.zero?
# Code here
end

If `discount` can be fractional numbers, you can use `#to_f` instead, to prevent the number from being rounded to zero.
Reply

#12
When dealing with a **database record**, I like to initialize all empty values with 0, using the migration helper:

add_column :products, :price, :integer, default: 0

Reply

#13
From Ruby 2.3.0 onward, you can combine the safe navigation operator (`&.`) with [`Numeric#nonzero?`](

[To see links please register here]

). `&.` returns `nil` if the instance was `nil` and `nonzero?` - if the number was `0`:

if discount&.nonzero?
# ...
end

Or postfix:

do_something if discount&.nonzero?
Reply

#14
def is_nil_and_zero(data)
data.blank? || data == 0
end

If we pass "" it will return false whereas blank? returns true.
Same is the case when data = false
blank? returns true for nil, false, empty, or a whitespace string.
So it's better to use blank? method to avoid empty string as well.
Reply

#15
if discount.nil? || discount == 0
[do something]
end
Reply

#16
Alternative solution is to use Refinements, like so:

module Nothingness
refine Numeric do
alias_method :nothing?, :zero?
end

refine NilClass do
alias_method :nothing?, :nil?
end
end

using Nothingness

if discount.nothing?
# do something
end
Reply

#17
ok, after 5 years have passed....

if discount.try :nonzero?
...
end

It's important to note that `try` is defined in the ActiveSupport gem, so it is not available in plain ruby.
Reply

#18
I prefer using a more cleaner approach :

val.to_i.zero?

`val.to_i` will return a `0` if **val** is a `nil`,

after that, all we need to do is check whether the final value is a **zero**.
Reply

#19
Yes, we do have a clean way in ruby.

discount.to_f.zero?
This check handles good amount of cases i.e. discount may be nil, discount may be int 0, discount may be float 0.0, discount may be string "0.0", "0".
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

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