How to check whether a string is an integer in Ruby? [duplicate] - ruby

This question already has answers here:
How to test if a string is basically an integer in quotes using Ruby
(19 answers)
Test if string is a number in Ruby on Rails
(13 answers)
Closed 9 years ago.
I have a string "1234223" and I want to check whether the value is an integer/number.
How can I do that in one line?
I have tried
1 =~ /^\d+$/
=> nil
"1a" =~ /^\d+$/
=> nil
Both line are returning nil

If you're attempting to keep similar semantics to the original post, use either of the following:
"1234223" =~ /\A\d+\z/ ? true : false
#=> true
!!("1234223" =~ /\A\d+\z/)
#=> true
A more idiomatic construction using Ruby 2.4's new Regexp#match? method to return a Boolean result will also do the same thing, while also looking a bit cleaner too. For example:
"1234223".match? /\A\d+\z/
#=> true

How about Integer("123") rescue nil ?

You can use regex
"123".match(/\A[+-]?\d+?(\.\d+)?\Z/) == nil ? false : true
It will also check for decimals.

"1234223".tap{|s| break s.empty? || s =~ /\D/}.!

Related

What does &.!= mean in Ruby? [duplicate]

This question already has answers here:
What does &. (ampersand dot) mean in Ruby?
(8 answers)
Closed 5 years ago.
action&.!=:click
Can somebody please explain to me what is the meaning of this in ruby and where I can get some explanations? I try to search ruby documentation, but no luck with this kind of 'chaining' operators
:click is symbol
!= is not equal
but I have no idea about &.
What looks like one operator in the middle (&.!=) is actually 1 operator and 1 method call : &. followed by != with :click as argument:
action &. != :click
It checks if action is not nil but distinct from :click:
action = nil
action&.!=:click
# => nil
action = :not_click
action&.!=:click
# => true
action = :click
action&.!=:click
# => false
action = false
action&.!=:click
# => true
It's an abusive way to use &. in my humble opinion. &. is called a "safe navigation operator", because it prevents you from calling undefined methods on nil objects.
!= is defined for any object though, so there's nothing safe about using &. before !=.
You could write :
!(action.nil? || action == :click)
or
!action.nil? && action != :click
or even:
![nil, :click].include?(action)

I need to write a regex in Ruby that returns true / false

I am trying to write a regex that takes a word and returns true for words starting with a vowel and returns false for words starting with a consonant. I have never written regex before, and I'm a little confused on how to write the expression. This is what I have so far:
def starts_with_a_vowel?(word)
if word.match(/\A+[aeiou]/) == true
return true
else
return false
end
end
Edit: So if word = "boat" , expression should return false. If word = "apple", expression should return true.
word.match? /\A[aeiou]/i is literally all you need. (ruby >= 2.4)
It matches the beginning of the string \A followed by a vowel [aeiou] in a case-insensitive manner i returning a bool word.match?
Before ruby 2.4 you have to use word.match and convert it to a bool, which is easiest done by logically negating it twice with !!
EDIT:
OK.. So.. I never tested the code I formerly wrote.. it was meant only as some suggestion how to use the match with regex, but it not worked at all.. (that code snippet is now attached to the end of my answer fyi)
this here should be the working one:
def starts_with_a_vowel?(word)
!!word.capitalize.match(/\A+[AEIOU]/)
end
..but how it was mentioned by Eric Duminil here below in comments, the method/function is
not needed
!!word.capitalize.match(/\A+[AEIOU]/) can be used directly..
it returns true or false
but there are surely other (maybe better) solutions too..
..and here is the NOT working code, which I formerly wrote:
def starts_with_a_vowel?(word)
return word.match(/\A+[aeiou]/).length > 0
end
..the match method returns nil when not match and because nil has no length method defined, it raises NoMethodError
Here are a couple of ways to do this.
#1
word = 'Ahoy'
!!(word[0] =~ /[aeiou]/i)
#=> true
word = 'hiya'
!!(word[0] =~ /[aeiou]/i)
#=> false
The regex reads, "match a vowel, case indifferently (/i)". !! converts a thruthy value to true and a falsy value (nil or false) to false:
!!0 = !(!0) = !(false) = true
!!nil = !(!nil) = !(true) = false
#2
word = 'Ahoy'
(word[0] =~ /[aeiou]/i) ? true : false
#=> true
word = 'hiya'
(word[0] =~ /[aeiou]/i) ? true : false
#=> false
You're doing a lot of extra work for no reason. First, you don't need to check for equality with true; just if *expression* does the trick.
But in this case you don't need if at all. A regex match already returns a value that can be interpreted as a Boolean. =~ returns the index of the match as an integer (which is "truthy"); String#match returns a MatchData object (which is also truthy). Everything in Ruby is truthy except false and nil, and nil is what both =~ and String#match return if there's no match. So all you have to do is turn the result of one of those into the corresponding Boolean value, which you can do with !!. For example:
def starts_with_a_vowel? word
!!(word =~ /^[aeiou]/)
end
That !! is read "not not", by the way. The ! operator by itself treats its argument as Boolean and returns its opposite as an actual Boolean; that is !(some truthy value) returns false (not nil), and !(some falsey value) returns true (not just some truthy value). So applying ! twice turns any truthy value into true and any falsey value (false or nil) into false.
Do you have to use a regular expression? Just asking cause Ruby already provides String#start_with?
vowels = %w(a e i o u)
"boat".start_with?(*vowels)
# => false
"apple".start_with?(*vowels)
#=> true
In Ruby, you almost never need anything to return true or false. For boolean logic and if/case/unless statements, truthy/falsey are good enough. Also, don't forget to use case-insensitive Regex (with //i). A is a vowel :
class String
def starts_with_a_vowel?
self =~ /\A[aeiou]/i
end
end
if "Airplane".starts_with_a_vowel?
puts "Indeed"
end
#=> "Indeed"
If for some reason you really need true/false :
class String
def starts_with_a_vowel?
!(self =~ /\A[aeiou]/i).nil?
end
end

Why does `defined?` keyword not return boolean? [duplicate]

This question already has answers here:
Why does `defined?` return a string or nil?
(2 answers)
Closed 7 years ago.
In ruby, most methods or keywords that end with ? return boolean values. And we except them to behave like this. Why does defined? keyword return somethings else? Or why is there ? at the end of it?
This question can be understood in two ways:
Why doesn't it simply return true or false?
It's because it encodes more information than simply if something is defined or not:
defined? Class # => "constant"
defined? 42 # => "expression"
defined? nil # => "nil"
defined? x # => nil
Why does it have ? at the end since as the convention goes, the question mark is reserved for predicates?
You are right that this is inconsistent. The most likely reasons are:
Almost always, you will use it as predicate anyway
if defined? x
# do something
end
The shortest alternative, which doesn't sound like a predicate I can think of is definition_type_of. Generally, you want to keep the reserved words in your language short
Developers chose to return something more meaningfull than true or false because the only case that breaks by not having boolean returned is explicit comparison:
defined?(:x) == true
# => always `false`
Such comparison is something you should usually not do, as logical operators like || and && are just as likely to return some truthy object instead of true. This is barely needed for anything.
The "defined?"-method can return more than "true" or "false". It tells you what type of variable it is if it's defined at all.
Check
Checking if a variable is defined?
and
http://ruby-doc.org/docs/keywords/1.9/Object.html#method-i-defined-3F

Whats the ruby !! operator? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What does !! mean in ruby?
I'm learning ruby/rails and found a tutorial with the following code example:
def role?(role)
return !!self.roles.find_by_name(role.to_s.camelize)
end
I don't have any idea for what the !! do, neither the !!self do.
I really googled about that, but doesn't find anything.
Can anyone give a short explanation? Thanks in advance.
It's the "not" operator (!) repeated twice, so that it's argument will be coerced to its negated boolean and then its corresponding boolean. Basically, it's a way to coerce any object into its boolean value.
!!false # => false
!!nil # => false
!!true # => true
!!{} # => true
!![] # => true
!!1 # => true
!!0 # => true (Surprised? Only 'false' and 'nil' are false in Ruby!)
It's usually employed to force-cast an arbitrary value into one of true or false.
This is often useful for converting between arbitrary numbers, strings, or potential nil values.
In your example this is extremely inefficient since an entire model is loaded only to be discarded. It would be better written as:
def role?(role)
self.roles.count_by_name(role.to_s.camelize) > 0
end
That query will return a singular value that is used for comparison purposes, the result of which is automatically a boolean.
This confirms that the operation will always return the boolena value
!!1 #gives you true
!!nil #gives you false
In ruby nil, false is consider as false and 0, 0.0 and other objects are consider as true

What's the difference between == and === when comparing 2 object [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
=== vs. == in Ruby
Fixnum == 2.class
#=> true
Fixnum === 2.class
#=> false
why === doesn't work? and how can I know the method .=== belong to(right now I guess it invoke the Object#==, or Object#===), but how can I make sure of that?
Duplicates:
=== vs. == in Ruby
What does the "===" operator do in Ruby?
=== vs. == in Ruby
Ruby compare objects
Case equality. See the documentation for Object#===. This method is usually overridden in subclasses of Object. For example, Module#===:
Case Equality--Returns true if anObject is an instance of mod or one of mod’s descendants. Of limited use for modules, but can be used in case statements to classify objects by class.
>> Module.new === Module
=> false
>> Module === Module.new
=> true
Regexp#=== is another one, in which case it's a synonym of =~:
a = "HELLO"
case a
when /^[a-z]*$/; print "Lower case\n"
when /^[A-Z]*$/; print "Upper case\n"
else; print "Mixed case\n"
end
An example in IRB:
>> "a" === /a/
=> false
>> /a/ === "a"
=> true
Remember, the first one returns false because you're doing === on String which isn't the same thing. In the second example we're doing === on Regexp
And finally, Range is quite a good one it calls include? on the Range object and passes your value in:
>> (1..100) === 3
=> true
>> (1..100) === 300
=> false
For a list of these, check out RubyDoc.info core documentation and search for === in the methods area in the left side frame
The == usually only checkes the values of both arguments, when ==== checks the types, too.

Resources