views:

84

answers:

3

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
+5  A: 

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.

Matchu
+3  A: 

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
Chuck Vose
+1  A: 

A compromise between readability and performance

!str.match(/do i match/).nil?
glebm
Could you replace the `!` with a `not`?
Andrew Grimm
Using 'not' in this very particular instance would be OK, but there is a difference in priority between ! and not. Try "puts !true" and "puts not true".
Trevoke