Jerome
Jerome

Reputation: 6189

Multiple Conditional Statement Execution in Ruby

The following statements need to be evaluated if their content is not nil and submitted. The receiving end does not accept nil values.

  :customer => {
    if [email protected]? :first_name => @transaction.nome,
    if [email protected]_name.nil? :last_name => @transaction.last_name,
    if [email protected]_id.nil? :country_name => @transaction.nation.name
    },

Without the condition a simple statement :first_name => @transaction.nome, is properly evaluated and the syntax with brackets and commas is proper. However, the introduction of the condition creates blanks in cases of nil values and generates a syntax error unexpected '}'.

How can this be overcome?

Upvotes: 1

Views: 172

Answers (3)

Paul.s
Paul.s

Reputation: 38728

You could kill some duplication by adding a small lambda

customer: {}.tap { |h|
  conditional_store = -> key, value { h.store(key, value) unless value.nil? }
  conditional_store[:firstName,    @transaction.name]
  conditional_store[:last_name,    @transaction.last_name]
  conditional_store[:country_name, @transaction.nation.name]
}

Upvotes: 1

kiddorails
kiddorails

Reputation: 13014

You can simply add the values and later filter them out. Will save you from all those checks:

:customer => {
    :first_name => @transaction.nome,
    :last_name => @transaction.last_name,
    :country_name => @transaction.nation.try(:name)
 }.reject{ |_, v| v.nil? }

Upvotes: 1

joelparkerhenderson
joelparkerhenderson

Reputation: 35453

One way is to build the hash:

h = {}
if @transaction.name      !=nil then h[:first_name]   = @transaction.name        end
if @transaction.last_name !=nil then h[:last_name]    = @transaction.last_name   end
if @transaction.nation_id !=nil then h[:country_name] = @transaction.nation.name end
:customer => h

If you know that your items are always truthy or nil, never falesy, then this is shorter:

if @transaction.name      then h[:first_name]   = @transaction.name        end
if @transaction.last_name then h[:last_name]    = @transaction.last_name   end
if @transaction.nation_id then h[:country_name] = @transaction.nation.name end

Upvotes: 1

Related Questions