In ruby, what is the best/most-elegant way to return a value such as:
#method returns true or false if 'do i match' is present in string
def method(str)
str =~ /do i match/
end
In ruby, what is the best/most-elegant way to return a value such as:
#method returns true or false if 'do i match' is present in string
def method(str)
str =~ /do i match/
end
Some people would do:
def foo
!!(str=~/do i match/)
end
# or
def foo
match = str=~/do i match/
!!match
end
The second !
runs the truthiness test and negates the answer, then the first !
negates it again to get the initial truthy result.
I rather prefer the more explicit syntax:
def foo
str =~ /do i match/ ? true : false
end
This does the truthiness, but to me feels clearer. Do what feels cleanest to you.
I may be a heretic for saying it but I think that they implicit return is beautiful. In this case it evaluates to true or false but I can see how people might think that this is unclear.
You could keep the implicit return and make this instead:
str =~ /do i match/ ? true : false
A compromise between readability and performance
!str.match(/do i match/).nil?