Ruby way to check if a string is not blank? - ruby

What's the best way to check if a variable is not blank in an else if condition in Ruby (not Rails)?
elsif not variable.to_s.empty?
# do something
end
or
elsif !variable.to_s.empty?
# do something
end
or
elsif variable.to_s.length > 0
# do something
end

string = ""
unless string.to_s.strip.empty?
# ...
end

I just found out that ''.empty? returns true but ' '.empty? returns false. Even to_s.length for ' ' is not zero.
Maybe it is better to use strip as ' '.strip.empty?

You can use either
unless var.empty?
#do sth
end
or
unless var == ""
#do sth
end
or all of these with if and a negator !.

The source of the empty? method is analogous to the following:
def empty?
return length == 0
end
So, you can safely use
any_string.length != 0
Anyway, using that code inside an else if is a bit verbose, I would encourage you to define the present? method inside the String class.
class String
def present?
!empty?
end
end
Now you can write your code the following way:
if some_condition
# do something
elsif variable.to_s.present?
# do something else
end
This way you get a clear code, without using negations or unless who are hard to read.
Of course, there is one problem here, I took the present? name (and method) from Rails. present? returns true if the object is not blank, but strings with tabs or spaces (white characters) are considered blanks. So, this present? will return true to for the following strings:
"".present? # => false
" ".present? # => true
"\t\n\r".present? # => true
" blah ".present? # => true
It depends on what you want, high chances are that you want to get true for the first 3 strings, and false for the later. You could use #RamanSM approach and use strip to avoid empty spaces
class String
def present?
!strip.empty?
end
end
now, present? returns false for strings with white spaces
"".present? # => false
" ".present? # => false
"\t\n\r".present? # => false
" blah ".present? # => true
Note: Consider that String.present? is present in the ActiveSupport library (which ships with rails) if you add ActiveSupport or use Rails you should use ActiveSupport implementation instead.

If you prefer if to unless...
If you know your variable will be a String...if str[0]
With nil check...if str && str[0] OR if str&.[](0) (I prefer the latter but it might look odd to some people and requires Ruby >= 2.3).
Also...I'd be very careful about calling #to_s on anything because you could end up with unexpected results. If str turns out to be something that you weren't expecting...
str = false
str.to_s[0] # => 'f' (i.e. truthy)
str.to_s.empty? # => false
str = nil
str.to_s[0] # => nil (i.e. falsey)
str.to_s.empty? # => true
I think this caution applies to usage of #to_s in the other answer here as well. Exceptions can be your friend.

For the string (say abc) which is not defined/undefined we should check for abc.nil?
otherwise abc.blank? will throw (NoMethodError) undefined method empty? for nil:NilClass error

Related

Not understanding the Boolean Logic to my method

I write the method capitalized(word) to be funneled into the .each function.
i use bang! to make the function work correctly but i don't understand why its working correctly.
The part that is really throwing me off is the !capitalized word line if statement. I don't understand the logic and how the method returns the answers that it does.
!false returns false in the method... why? And !true it returns true.
Whats the best way to understand this concept.
I have tried taking out the bang and putting it back in to see its effect.
And it just confuses me. Thank you for your help.
# A name is valid is if satisfies all of the following:
# - contains at least a first name and last name, separated by spaces
# - each part of the name should be capitalized
#
# Hint: use str.upcase or str.downcase
# "a".upcase # => "A"
def is_valid_name(str)
name = str.split(' ')
if name.length < 2
return false
end
name.each do |word|
if !capitalized(word)
return false
end
end
return true
end
def capitalized(word)
if word[0] == word[0].upcase && word[1..-1]== word[1..-1].downcase
return true
else
return false
end
end
puts is_valid_name("Kush Patel") # => true
puts is_valid_name("Daniel") # => false
puts is_valid_name("Robert Downey Jr") # => true
puts is_valid_name("ROBERT DOWNEY JR") # => false
The purpose of the part of the code you struggling with, is to check whether all of the elements of the name are capitalised. There are two ways you can approach that problem:
Find any element that is not capitalised.
If such element exists, that means name is not valid, so method is_valid_name should return false. This is the approach used in you code:
def is_valid_name(str)
#...
name.each do |word| #1
if !capitalized(word) #2
return false #3
end
end
return true #4
end
Iterate over every part of the name
Check if word is capitalized. We want to break only when we find invalid (not capitalized) word. That occurs when capitalized(word) returns false: so condition if !capitalized(word) is actually if !false, which is equal to if true.
We entered, that means our word is not valid, so we return false from is_valid_name method.
Check if all elements are capitalized
This is more straightforward solution. We just want to check, if method capitalized(word) returns true for all of the elements of the name.
To achieve that, we can use method all?, which returns true if condition in the block returns true for every element; otherwise false. So we can replace all the code above with single line:
name.all?{|word| capitalized(word) }
Final implementation of the validation method can look like that:
def is_valid_name(str)
name = str.split(' ')
name.length < 2 && name.all?{|word| capitalized(word)}
end
Hope it helps you!
!false returns false in the method... why?
I'm assuming you mean this one:
if !capitalized(word)
return false
end
"If capitalize returns false, why do we return false", this question? Because if a word is not capitalized, the name is invalid. That's the given business logic.

Ruby code to check for Integer [duplicate]

I need a function, is_an_integer, where
"12".is_an_integer? returns true.
"blah".is_an_integer? returns false.
How can I do this in Ruby? I would write a regex but I'm assuming there is a helper for this that I am not aware of.
Well, here's the easy way:
class String
def is_integer?
self.to_i.to_s == self
end
end
>> "12".is_integer?
=> true
>> "blah".is_integer?
=> false
I don't agree with the solutions that provoke an exception to convert the string - exceptions are not control flow, and you might as well do it the right way. That said, my solution above doesn't deal with non-base-10 integers. So here's the way to do with without resorting to exceptions:
class String
def integer?
[ # In descending order of likeliness:
/^[-+]?[1-9]([0-9]*)?$/, # decimal
/^0[0-7]+$/, # octal
/^0x[0-9A-Fa-f]+$/, # hexadecimal
/^0b[01]+$/ # binary
].each do |match_pattern|
return true if self =~ match_pattern
end
return false
end
end
You can use regular expressions. Here is the function with #janm's suggestions.
class String
def is_i?
!!(self =~ /\A[-+]?[0-9]+\z/)
end
end
An edited version according to comment from #wich:
class String
def is_i?
/\A[-+]?\d+\z/ === self
end
end
In case you only need to check positive numbers
if !/\A\d+\z/.match(string_to_check)
#Is not a positive number
else
#Is all good ..continue
end
You can use Integer(str) and see if it raises:
def is_num?(str)
!!Integer(str)
rescue ArgumentError, TypeError
false
end
It should be pointed out that while this does return true for "01", it does not for "09", simply because 09 would not be a valid integer literal. If that's not the behaviour you want, you can add 10 as a second argument to Integer, so the number is always interpreted as base 10.
Ruby 2.6.0 enables casting to an integer without raising an exception, and will return nil if the cast fails. And since nil mostly behaves like false in Ruby, you can easily check for an integer like so:
if Integer(my_var, exception: false)
# do something if my_var can be cast to an integer
end
"12".match(/^(\d)+$/) # true
"1.2".match(/^(\d)+$/) # false
"dfs2".match(/^(\d)+$/) # false
"13422".match(/^(\d)+$/) # true
You can do a one liner:
str = ...
int = Integer(str) rescue nil
if int
int.times {|i| p i}
end
or even
int = Integer(str) rescue false
Depending on what you are trying to do you can also directly use a begin end block with rescue clause:
begin
str = ...
i = Integer(str)
i.times do |j|
puts j
end
rescue ArgumentError
puts "Not an int, doing something else"
end
class String
def integer?
Integer(self)
return true
rescue ArgumentError
return false
end
end
It isn't prefixed with is_. I find that silly on questionmark methods, I like "04".integer? a lot better than "foo".is_integer?.
It uses the sensible solution by sepp2k, which passes for "01" and such.
Object oriented, yay.
The Best and Simple way is using Float
val = Float "234" rescue nil
Float "234" rescue nil #=> 234.0
Float "abc" rescue nil #=> nil
Float "234abc" rescue nil #=> nil
Float nil rescue nil #=> nil
Float "" rescue nil #=> nil
Integer is also good but it will return 0 for Integer nil
I prefer:
config/initializers/string.rb
class String
def number?
Integer(self).is_a?(Integer)
rescue ArgumentError, TypeError
false
end
end
and then:
[218] pry(main)> "123123123".number?
=> true
[220] pry(main)> "123 123 123".gsub(/ /, '').number?
=> true
[222] pry(main)> "123 123 123".number?
=> false
or check phone number:
"+34 123 456 789 2".gsub(/ /, '').number?
A much simpler way could be
/(\D+)/.match('1221').nil? #=> true
/(\D+)/.match('1a221').nil? #=> false
/(\D+)/.match('01221').nil? #=> true
Personally I like the exception approach although I would make it a little more terse:
class String
def integer?(str)
!!Integer(str) rescue false
end
end
However, as others have already stated, this doesn't work with Octal strings.
This might not be suitable for all cases simplely using:
"12".to_i => 12
"blah".to_i => 0
might also do for some.
If it's a number and not 0 it will return a number. If it returns 0 it's either a string or 0.
def isint(str)
return !!(str =~ /^[-+]?[1-9]([0-9]*)?$/)
end
Here's my solution:
# /initializers/string.rb
class String
IntegerRegex = /^(\d)+$/
def integer?
!!self.match(IntegerRegex)
end
end
# any_model_or_controller.rb
'12345'.integer? # true
'asd34'.integer? # false
And here's how it works:
/^(\d)+$/is regex expression for finding digits in any string. You can test your regex expressions and results at http://rubular.com/.
We save it in a constant IntegerRegex to avoid unnecessary memory allocation everytime we use it in the method.
integer? is an interrogative method which should return true or false.
match is a method on string which matches the occurrences as per the given regex expression in argument and return the matched values or nil.
!! converts the result of match method into equivalent boolean.
And declaring the method in existing String class is monkey patching, which doesn't change anything in existing String functionalities, but just adds another method named integer? on any String object.
Ruby 2.4 has Regexp#match?: (with a ?)
def integer?(str)
/\A[+-]?\d+\z/.match? str
end
For older Ruby versions, there's Regexp#===. And although direct use of the case equality operator should generally be avoided, it looks very clean here:
def integer?(str)
/\A[+-]?\d+\z/ === str
end
integer? "123" # true
integer? "-123" # true
integer? "+123" # true
integer? "a123" # false
integer? "123b" # false
integer? "1\n2" # false
Expanding on #rado's answer above one could also use a ternary statement to force the return of true or false booleans without the use of double bangs. Granted, the double logical negation version is more terse, but probably harder to read for newcomers (like me).
class String
def is_i?
self =~ /\A[-+]?[0-9]+\z/ ? true : false
end
end
For more generalised cases (including numbers with decimal point),
you can try the following method:
def number?(obj)
obj = obj.to_s unless obj.is_a? String
/\A[+-]?\d+(\.[\d]+)?\z/.match(obj)
end
You can test this method in an irb session:
(irb)
>> number?(7)
=> #<MatchData "7" 1:nil>
>> !!number?(7)
=> true
>> number?(-Math::PI)
=> #<MatchData "-3.141592653589793" 1:".141592653589793">
>> !!number?(-Math::PI)
=> true
>> number?('hello world')
=> nil
>> !!number?('hello world')
=> false
For a detailed explanation of the regex involved here, check out this blog article :)
One liner in string.rb
def is_integer?; true if Integer(self) rescue false end
I'm not sure if this was around when this question is asked but
for anyone that stumbles across this post, the simplest way is:
var = "12"
var.is_a?(Integer) # returns false
var.is_a?(String) # returns true
var = 12
var.is_a?(Integer) # returns true
var.is_a?(String) # returns false
.is_a? will work with any object.

Why are these two methods that seem the same operate differently?

My method exist­s_else takes two parameters: base and fallback. If base is nil, it returns fallback. If it's not nil, it returns base. A call to exist­s_else(true, false) should return true.
If I use a standard looking if-statement, true is returned like I thought it would be:
def exist­s_else(bas­e, fallb­ack)
unless base.­nil?
base
else
fallb­ack
end
end
a = true
exists_els­e( a, false­ )
# => true
If I use the inline implementation shown below, it returns false.
def exist­s_else(base, fallback)
base unles­s base.nil­? else fallback
end
a = true
exists_els­e( a, false­ )
# => false
Why does does it return false in the inline implementation?
Your assertion that
base unles­s base.nil­? else fallback
is supposed to be equivalent to the long-form unless statement is not true; in fact, you cannot use else inside a post condition. Ruby is interpreting the code as:
def exist­s_else(base, fallback)
base unles­s base.nil­?
else fallback
end
If you type this (or the version without the newline, as in your question) into IRB, Ruby gives the following warning:
warning: else without rescue is useless
That is to say, Ruby is trying to interpret the else as part of exception handling code, as in
def exists_else(base, fallback)
base unless base.nil
rescue ArgumentError => e
# code to handle ArgumentError here
else
# code to handle other exceptions here
end
You can not use an else statement when you're trying to do it in one line. When an else is necessary you must use the extended version.
Ruby thinks that the else in this case is related to error handling. You have to stick to your initial unless-end method.
I prefer this syntax to evaluate true/false checks:
condition(s) ? true_value : false_value
In your case, it would look like:
def exists_else(base, fallback)
base.nil? ? fallback : base
end
a = true
puts exists_else(a, false) # => true

Best ruby idiom for "nil or zero"

I am looking for a concise way to check a value to see if it is nil or zero. Currently I am doing something like:
if (!val || val == 0)
# Is nil or zero
end
But this seems very clumsy.
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
From Ruby 2.3.0 onward, you can combine the safe navigation operator (&.) with Numeric#nonzero?. &. returns nil if the instance was nil and nonzero? - if the number was 0:
unless val&.nonzero?
# Is nil or zero
end
Or postfix:
do_something unless val&.nonzero?
If you really like method names with question marks at the end:
if val.nil? || val.zero?
# do stuff
end
Your solution is fine, as are a few of the other solutions.
Ruby can make you search for a pretty way to do everything, if you're not careful.
First off I think that's about the most concise way you can check for that particular condition.
Second, to me this is a code smell that indicates a potential flaw in your design. Generally nil and zero shouldn't mean the same thing. If possible you should try to eliminate the possibility of val being nil before you hit this code, either by checking that at the beginning of the method or some other mechanism.
You might have a perfectly legitimate reason to do this in which case I think your code is good, but I'd at least consider trying to get rid of the nil check if possible.
You can use the Object.nil? to test for nil specifically (and not get caught up between false and nil). You can monkey-patch a method into Object as well.
class Object
def nil_or_zero?
return (self.nil? or self == 0)
end
end
my_object = MyClass.new
my_object.nil_or_zero?
==> false
This is not recommended as changes to Object are difficult for coworkers to trace, and may make your code unpredictable to others.
nil.to_i returns zero, so I often do this:
val.to_i.zero?
However, you will get an exception if val is ever an object that does not respond_to #to_i.
I believe your code is incorrect; it will in fact test for three values: nil, false, and zero. This is because the !val expression is true for all values that are false, which in Ruby is nil and false.
The best I can come up with right now is
if val == nil || val == 0
# do stuff
end
Which of course is not very clever, but (very) clear.
My solution also use Refinements, minus the conditionals.
module Nothingness
refine Numeric do
alias_method :nothing?, :zero?
end
refine NilClass do
alias_method :nothing?, :nil?
end
end
using Nothingness
if val.nothing?
# Do something
end
Short and clear
[0, nil].include?(val)
Shortest and best way should be
if val&.>(0)
# do something
end
For val&.>(0)
it returns nil when val is nil since > basically is also a method, nil equal to false in ruby. It return false when val == 0.
Rails does this via attribute query methods, where in addition to false and nil, 0 and "" also evaluate to false.
if (model.attribute?) # => false if attribute is 0 and model is an ActiveRecord::Base derivation
However it has its share of detractors. http://www.joegrossberg.com/archives/002995.html
To be as idiomatic as possible, I'd suggest this.
if val.nil? or val == 0
# Do something
end
Because:
It uses the nil? method.
It uses the "or" operator, which is preferable to ||.
It doesn't use parentheses, which are not necessary in this case. Parentheses should only be used when they serve some purpose, such as overriding the precedence of certain operators.
I deal with this by defining an "is?" method, which I can then implement differently on various classes. So for Array, "is?" means "size>0"; for Fixnum it means "self != 0"; for String it means "self != ''". NilClass, of course, defines "is?" as just returning nil.
You can use case if you like:
case val with nil, 0
# do stuff
end
Then you can use anything that works with ===, which is nice sometimes. Or do something like this:
not_valid = nil, 0
case val1 with *not_valid
# do stuff
end
#do other stuff
case val2 with *not_valid, false #Test for values that is nil, 0 or false
# do other other stuff
end
It's not exactly good OOP, but it's very flexible and it works. My ifs usually end up as cases anyway.
Of course Enum.any?/Enum.include? kind of works too ... if you like to get really cryptic:
if [0, nil].include? val
#do stuff
end
The right thing to do is of course to define a method or function. Or, if you have to do the same thing with many values, use a combination of those nice iterators.
I really like Rails blank? method for that kind of things, but it won't return true for 0. So you can add your method:
def nil_zero?
if respond_to?(:zero?)
zero?
else
!self
end
end
And it will check if some value is nil or 0:
nil.nil_zero?
=> true
0.nil_zero?
=> true
10.nil_zero?
=> false
if val.nil_zero?
#...
end
Instead of monkey patching a class, you could use refinements starting in Ruby 2.1. Refinements are similar to monkey patching; in that, they allow you to modify the class, but the modification is limited to the scope you wish to use it in.
This is overkill if you want to do this check once, but if you are repeating yourself it's a great alternative to monkey patching.
module NilOrZero
refine Object do
def nil_or_zero?
nil? or zero?
end
end
end
using NilOrZero
class Car
def initialize(speed: 100)
puts speed.nil_or_zero?
end
end
car = Car.new # false
car = Car.new(speed: nil) # true
car = Car.new(speed: 0) # true
Refinements were changed in the last minute to be scoped to the file. So earlier examples may have shown this, which will not work.
class Car
using NilOrZero
end
This is very concise:
if (val || 0) == 0
# Is nil, false, or zero.
end
It works as long as you don't mind treating false the same as nil. In the projects I've worked on, that distinction only matters once in a while. The rest of the time I personally prefer to skip .nil? and have slightly shorter code.
[Update: I don't write this sort of thing any more. It works but is too cryptic. I have tried to set right my misdeeds by changing the few places where I did it.]
By the way, I didn't use .zero? since this raises an exception if val is, say, a string. But .zero? would be fine if you know that's not the case.
This evaluates to true for nil and zero: nil.to_s.to_d == 0
unless (val || 0).zero?
# do stufff
end
In a single stretch you can do this:
[do_something] if val.to_i == 0
nil.to_i will return 0
Another solution:
if val.to_i == 0
# do stuff
end
val ||= 0
if val == 0
# do something here
end

Is There a Better Way of Checking Nil or Length == 0 of a String in Ruby?

Is there a better way than the following to check to see if a string is nil OR has a length of 0 in Ruby?
if !my_string || my_string.length == 0
return true
else
return false
end
In C# there's the handy
string.IsNullOrEmpty(myString)
Anything similar to that in Ruby?
When I'm not worried about performance, I'll often use this:
if my_string.to_s == ''
# It's nil or empty
end
There are various variations, of course...
if my_string.to_s.strip.length == 0
# It's nil, empty, or just whitespace
end
If you are willing to require ActiveSupport you can just use the #blank? method, which is defined for both NilClass and String.
I like to do this as follows (in a non Rails/ActiveSupport environment):
variable.to_s.empty?
this works because:
nil.to_s == ""
"".to_s == ""
An alternative to jcoby's proposal would be:
class NilClass
def nil_or_empty?
true
end
end
class String
def nil_or_empty?
empty?
end
end
As it was said here before Rails (ActiveSupport) have a handy blank? method and it is implemented like this:
class Object
def blank?
respond_to?(:empty?) ? empty? : !self
end
end
Pretty easy to add to any ruby-based project.
The beauty of this solution is that it works auto-magicaly not only for Strings but also for Arrays and other types.
variable.blank? will do it.
It returns true if the string is empty or if the string is nil.
nil? can be omitted in boolean contexts. Generally, you can use this to replicate the C# code:
return my_string.nil? || my_string.empty?
First of all, beware of that method:
As Jesse Ezel says:
Brad Abrams
"The method might seem convenient, but most of the time I have found that this situation arises from trying to cover up deeper bugs.
Your code should stick to a particular protocol on the use of strings, and you should understand the use of the protocol in library code and in the code you are working with.
The NullOrEmpty protocol is typically a quick fix (so the real problem is still somewhere else, and you got two protocols in use) or it is a lack of expertise in a particular protocol when implementing new code (and again, you should really know what your return values are)."
And if you patch String class... be sure NilClass has not been patch either!
class NilClass
def empty?; true; end
end
Every class has a nil? method:
if a_variable.nil?
# the variable has a nil value
end
And strings have the empty? method:
if a_string.empty?
# the string is empty
}
Remember that a string does not equal nil when it is empty, so use the empty? method to check if a string is empty.
Another option is to convert nil to an empty result on the fly:
(my_string||'').empty?
Konrad Rudolph has the right answer.
If it really bugs you, monkey patch the String class or add it to a class/module of your choice. It's really not a good practice to monkey patch core objects unless you have a really compelling reason though.
class String
def self.nilorempty?(string)
string.nil? || string.empty?
end
end
Then you can do String.nilorempty? mystring
Check for Empty Strings in Plain Ruby While Avoiding NameError Exceptions
There are some good answers here, but you don't need ActiveSupport or monkey-patching to address the common use case here. For example:
my_string.to_s.empty? if defined? my_string
This will "do the right thing" if my_string is nil or an empty string, but will not raise a NameError exception if my_string is not defined. This is generally preferable to the more contrived:
my_string.to_s.empty? rescue NameError
or its more verbose ilk, because exceptions should really be saved for things you don't expect to happen. In this case, while it might be a common error, an undefined variable isn't really an exceptional circumstance, so it should be handled accordingly.
Your mileage may vary.
If you are using rails, you can use #present?
require 'rails'
nil.present? # ==> false (Works on nil)
''.present? # ==> false (Works on strings)
' '.present? # ==> false (Works on blank strings)
[].present? # ==> false(Works on arrays)
false.present? # ==> false (Works on boolean)
So, conversely to check for nil or zero length use !present?
!(nil.present?) # ==> true
!(''.present?) # ==> true
!(' '.present?) # ==> true
!([].present?) # ==> true
!(false.present?) # ==> true
Have you tried Refinements?
module Nothingness
refine String do
alias_method :nothing?, :empty?
end
refine NilClass do
alias_method :nothing?, :nil?
end
end
using Nothingness
return my_string.nothing?
In rails you can try #blank?.
Warning: it will give you positives when string consists of spaces:
nil.blank? # ==> true
''.blank? # ==> true
' '.blank? # ==> true
'false'.blank? # ==> false
Just wanted to point it out. Maybe it suits your needs
UPD. why am i getting old questions in my feed?
Sorry for necroposting.
For code golfers:
if my_string=~/./
p 'non-empty string'
else
p 'nil or empty string'
end
Or if you're not a golfer (requires ruby 2.3 or later):
if my_string&.size&.positive?
# nonzero? also works
p 'non-empty string'
else
p 'nil or empty string'
end

Resources