Tintin81
Tintin81

Reputation: 10225

How to improve this Ruby case switch statement?

I am wondering if there's a more elegant way to say this in Ruby:

FREE_PLAN_MAXIMUM = 1
BASIC_PLAN_MAXIMUM = 10
PREMIUM_PLAN_MAXIMUM = 100

def maximum_entries_per_month
  case plan
  when "premium"
    PREMIUM_PLAN_MAXIMUM
  when "basic"
    BASIC_PLAN_MAXIMUM
  else
    FREE_PLAN_MAXIMUM
  end 
end

I don't like the repetition of premium and basic inside the function. What might be an alternative?

Upvotes: 1

Views: 105

Answers (4)

sawa
sawa

Reputation: 168269

You don't need a method. Just have a hash:

maximum_entries_per_month = Hash.new(1).merge{"premium" => 100, "basic" => 10}

and call:

maximum_entries_per_month[plan]

Upvotes: 1

arieljuod
arieljuod

Reputation: 15848

what about:

FREE_PLAN_MAXIMUM = 1
BASIC_PLAN_MAXIMUM = 10
PREMIUM_PLAN_MAXIMUM = 100
PLANS = {'premium' => PREMIUM_PLAN_MAXIMUM, 'basic' => BASIC_PLAN_MAXIMUM, 'free' => FREE_PLAN_MAXIMUM}

def maximum_entries_per_month
  PLANS[plan] or FREE_PLAN_MAXIMUM
end

that "or FREE_PLAN_MAXIMUM" will catch any plan that's not "premium", "basic" or "free", if you are sure you only have those three plans just remove that part

EDIT: this way you keep your other constants working

EDIT2: if you don't want to add more constants and you are sure plan is one of those, you can do:

def maximum_entries_per_month
  self.class.const_get("#{plan.upcase}_PLAN_MAXIMUM")
end

Upvotes: 0

Chris Cashwell
Chris Cashwell

Reputation: 22899

Use Hash#fetch, which allows for a default value, instead of a case statement.

PLAN_MAXIMUMS = { free: 1, basic: 10, premium: 100 }

def maximum_entries_per_month
  PLAN_MAXIMUMS.fetch(plan.to_sym, PLAN_MAXIMUMS[:free])
end

Upvotes: 3

spike
spike

Reputation: 10014

It depends on the rest of your code, especially whether you're using those constants in other places. One pattern I've found nice for this kind of thing is a hash, though.

PLAN_MAXIMUMS = { free: 1, basic: 10, premium: 100 }

def maximum_entries_per_month
  PLAN_MAXIMUMS[plan.to_sym] || PLAN_MAXIMUMS[:free]
end 

Upvotes: 3

Related Questions