Best ruby idiom for nil or zero
Objects have a nil? method.
if val.nil? || val == 0
[do something]
end
Or, for just one instruction:
[do something] if val.nil? || val == 0
Idiomatic Ruby filter for nil-or-empty?
In Rails, you can do reject(&:blank?)
, or equivalently, select(&:present?)
.
If this is not for a Rails app, and you do this a lot, I'd advise you to define your own helper on String
or whatever else you are filtering.
class String
alias :blank? :empty?
end
class NilClass
def blank?
true
end
end
Ruby idiom for foo.nil? ? nil : foo.to_i?
Or a little bit shorter (if you dont expect foo
to be false
)
def bar(foo)
foo.to_i if foo
end
Checking if a variable is not nil and not zero in ruby
unless discount.nil? || discount == 0
# ...
end
Rails 3.1: Ruby idiom to prevent .each from throwing exception if nil?
Can't believe no one has suggested this yet:
(@myvar.phonelist || []).each do |phone|
...
If phonelist
is nil
, the each
will loop on the empty array, executing the block zero times.
HOWEVER, this will still throw an exception if phonelist
is not an enumerable (e.g. an array).
How might I treat nil values as zero when adding numbers?
As @jforberg points out, you can just use the #to_i
method which will return 0 for nil.
def calculate_the_thing(hsh)
hsh[:x].to_i + hsh[:y].to_i + hsh[:z].to_i
end
Alternatively, you can also define the hash with an automatic default value...
hsh = Hash.new{0}
But if you have a method that explicitly puts nil
as a hash value that will override the default value.
Is there a Ruby, or Ruby-ism for not_nil? opposite of nil? method?
when you're using ActiveSupport, there's user.present?
http://api.rubyonrails.org/classes/Object.html#method-i-present%3F, to check just for non-nil, why not use
def logged_in?
user # or !!user if you really want boolean's
end
Ruby: Idiom for create and increment
The question is clear:
- A variable is known to hold
nil
or an integer. Ifnil
the variable is to be set equal to1
, else it is to be set equal to its value plus1
. - What is the best way to implement this in Ruby?
First, two points.
- The question states, "If it is nil, it should be initialized with
1
.". This contradicts the statement that the variable is known to benil
or an integer, meaning that it has already been initialized, or more accurately, defined. In the case of an instance variable, this distinction is irrelevant as Ruby initializes undefined instance variables tonil
when they are referenced as rvalues. It's an important distinction for local variables, however, as an exception is raised when an undefined local variable is referenced as an rvalue. - The comments largely address situations where the variable holds an object other than
nil
or aninteger
. They are therefore irrelevant. If the OP wishes to broaden the question to allow the variable to hold objects other thannil
or an integer (an array or hash, for example), a separate question should be asked.
What criteria should be used in deciding what code is best? Of the various possibilities that have been mentioned, I do not see important differences in efficiency. Assuming that to be the case, or that relative efficiency is not important in the application, we are left with readability (and by extension, maintainability) as the sole criterion. If x
equals nil
or an integer, or is an undefined instance variable, perhaps the clearest code is the following:
x = 0 if x.nil?
x += 1
or
x = x.nil? ? 1 : x+1
Ever-so-slightly less readable:
x = (x || 0) + 1
and one step behind that:
x = x.to_i + 1
which requires the reader to know that nil.to_i #=> 0
.
The OP may regard these solutions as "clumsy", but I think they are all beautiful.
Can an expression be written that references x
but once? I can't think of a way and one has not been suggested in the comments, so if there is a way (doubtful, I believe) it probably would not meet the test for readability.
Consider now the case where the local variable x
may not have been defined. In that case we might write:
x = (defined?(x) ? (x || 0) : 0) + 1
defined? is a Ruby keyword.
Related Topics
Count Number of Days Between Two Dates
Executing User-Supplied Ruby Code on a Web Server
Writing Over Previously Output Lines in the Command Prompt with Ruby
How to Sort in Ruby/Rails on Two Fields
How to Create an Array in Ruby with Default Values
How to Use the Rails Helper "Distance_Of_Time_In_Words" in Plain Old Ruby (Non-Rails)
Rspec: How to Test If a Method Was Called
How to Generate Rdoc for (All Of) Rails
How to Use Redis in a Multi-Threaded Rails Environment? (Puma/Sidekiq)
How to Remove a Substring After a Certain Character in a String Using Ruby
Rmagick Remove White Background from Image and Make It Transparent