Alexandre
Alexandre

Reputation: 13308

Boolean values in Ruby

I have a method that has a boolean value as a parameter. I'm aware it's better to avoid boolean values. Anyway in my case it's most efficient way.

Well, here is a method:

  def some_method(include_some_values = false)
          #do some workcountries = []
          if include_some_values 
             #do some additional work  
           end
           #return value
    end

calling (haml)

= form_for @address do |f|
  = f.select :fied1, MyModel.some_method(true) #it's okay

However if I call it as

= f.select :fied1, MyModel.some_method true 

or

= f.select :fied1, MyModel.some_method :true 

or

= f.select :fied1, MyModel.some_method false 

or

= f.select :fied1, MyModel.some_method :false 

then it's not going to work. Why?

Upvotes: 1

Views: 1444

Answers (2)

BaronVonBraun
BaronVonBraun

Reputation: 4293

If your issue involves problems when not using parentheses, it has nothing to do with booleans and everything to do with the Ruby parser.

Passing a method as a parameter to another method requires parentheses in some cases:

def a_method(value)
   puts value
end

def one_argument(value)
   puts value
end

def two_arguments(value1, value2)
   puts value1 + value2
end

# These snippets work fine
one_argument a_method 15
one_argument a_method(15)
two_arguments 999, a_method(15)
# ... etc ...

# This one doesn't
two_arguments 999, a_method 15

That last example (which is like what you're doing in your question) is ambiguous to the Ruby parser, so you get an error.

Upvotes: 4

Roland Mai
Roland Mai

Reputation: 31077

Probably

= f.select :fied1, MyModel.some_method true

is interpreted as:

= f.select(:fied1, MyModel.some_method) true

So just use parenthesizes to avoid ambiguity.

PS: :true is a symbol, so there's no reason to fiddle with symbols if your dealing with booleans.

Upvotes: 4

Related Questions