mlzboy
mlzboy

Reputation: 14691

Better way to set default values?

Can we make the following Ruby code shorter, and at the same time more readable?

height = do_some_calc
height = 128 if height == 0

Upvotes: 2

Views: 235

Answers (6)

user229044
user229044

Reputation: 239301

This is technically shorter if not very readable:

(height = do_some_call) == 0 and height = 128

I would say keep it the way you have it, your way seems to be the most concise and readable.

Upvotes: -4

EmFi
EmFi

Reputation: 23450

If you're willing to alter do_some_calc to return false or nil instead of 0, then you're in business.

height = do_some_calc || 128

If you can't alter do_some_calc to return false or nil when it would normally return 0, then you could wrap it, but you're not saving many characters in the long run. With the exception of the case where you have many places where you set defaults.

This wrapper would return false if do_some_calc returned 0 and the output of do_some_calc in all other cases.

def my_do_some_calc
   temp = do_some_calc 
   temp != 0 && temp
end

Putting it all together gives:

height = my_do_some_calc || 128

Upvotes: 2

khanh
khanh

Reputation: 4606

You can do as follows

height = do_some_calc.zero? ? 128 : do_some_calc 

Upvotes: 0

the Tin Man
the Tin Man

Reputation: 160551

Shorter? Not and be functional.

  height = (h = do_some_calc).zero? ? 128 : h 

as in:

def do_some_calc
  rand 100
end

10.times do 
  height = (h = do_some_calc).zero? ? 128 : h 
  puts height
end
# >> 3
# >> 95
# >> 89
# >> 82
# >> 31
# >> 4
# >> 82
# >> 99
# >> 11
# >> 64

Upvotes: 1

theIV
theIV

Reputation: 25774

Maybe something along the lines of:

STANDARD_HEIGHT = 128
def do_some_calc
  height = 0
  #calculate our height...
  height = height == 0 ? STANDARD_HEIGHT : calculated_height
end

I think there needs to be more context given to the 128, hence the constant. I also think that do_some_calc should hide away the fact that if it does equal 0, it really should equal our DEFAULT_HEIGHT.

EDIT: To answer your implied question (that I edited as such), we can make it shorter by making do_some_calc longer.

Upvotes: 0

Nakilon
Nakilon

Reputation: 35084

height = 128 if 0 == height = do_some_calc

It's the only way I know, if do_some_calc must be evaluated only once.

Upvotes: 7

Related Questions