Sahil Rally
Sahil Rally

Reputation: 541

Setting Hash Key value based on if-else condition in a cleaner way

I am looking for cleaner way to write this

{
  if(condition)
    a: 25
  elseif
    a: 32
  end

  if(condition)
    b: 25
  elseif
    b: 32
  end

}

I have various keys in a hash like this which are all based on the same condition.

Query 1: Is there a better/cleaner ruby way if the condition is same for all keys?

Query 2: Is there a better/cleaner ruby way if the condition is different for all keys?

I tried writing method which accepts the condition,object1,object2 as arguments and returns object1 if the condition is true otherwise object2. It is not working.

def conditional(condition,object1,object2)
if(condition)
  object1
elsif
  object2
end

end

Upvotes: 1

Views: 2034

Answers (5)

wiesion
wiesion

Reputation: 2445

I suggest to keep getting stuff done instead of focussing way too much on what rubocop wants. I can agree that extra lengthy lines do not look nice and they should be avoided WHENEVER POSSIBLE - but sometimes it can happen that strings (for configurations of URLs etc) can get a bit lengthy, so just deactivate the line length check for this blocks, and activate it again afterwards.

# rubocop:disable LineLength
{ a: "blablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablablabla" }
# rubocop:enable LineLength

Upvotes: 1

AnkitG
AnkitG

Reputation: 6568

A little more readable with tap and ternary

hsh = Hash.new

hsh.tap do |hsh_instance|
  hsh_instance[:a] = get_value_a
  hsh_instance[:b] = get_value_b
end

def get_value_a
   condition_true? ? value_1_a : value_2_a
end

def get_value_b
   condition_true? ? value_1_b : value_2_b
end

Upvotes: 0

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230336

If condition is the same, then you construct entire hashes in the if.

if condition
  { a: 1, b: 2 }
else
  { a: 3, b: 4 }
end

If conditions are specific, I would try extracting the logic in small specialized methods.

{ a: value_for_a, b: value_for_b }

Upvotes: 3

Derek Nagy
Derek Nagy

Reputation: 48

Try a ternary expression

a = condition ? 25 : 32

Upvotes: 0

LazyNick7
LazyNick7

Reputation: 83

Maybe ternary operator will help?

It's an expression that works like:

{ if_this_is_a_true_value ? then_the_result_is_this : else_it_is_this }

Upvotes: 0

Related Questions