Home > database >  How to write a helper method in ruby to reduce code duplication?
How to write a helper method in ruby to reduce code duplication?

Time:11-18

I'm really new to ruby and tbh even programming. I'm trying to use the following code in order to perform the same operation for multiple flavors as follows using a switch case -

def Icecream
...
...
Value = case flavors
         when 'STRAWBERRY'
         (shop.straw * 1000).round(5)
         when 'CHOCOLATE'
         (shop.choc * 1000).round(5)
         when 'VANILLA'
         (shop.van * 1000).round(5)
         when 'MANGO'
         (shop.man * 1000).round(5)
         end
...
...
end

How can I create a helper method to reduce the code duplication? This maybe a silly question but would be really helpful for learning. Thanks in advance!

So, shop.straw gets me a double value which I'm multiplying with 1000 and rounding.

CodePudding user response:

You could do a couple of things. The easiest solution would probably be one that takes the "double value" as an argument like so:

def calculation(flavor)
  (flavor * 1000).round(5)
end

Then, your case statement would be:

Value = case flavors
        when 'STRAWBERRY'
          calculation(show.straw)
        when 'CHOCOLATE'
          calculation(show.choc)
        when 'VANILLA'
          calculation(show.van)
        when 'MANGO'
          calculation(show.man)
        end

You could probably simply it further if you needed, but that's the main idea.

CodePudding user response:

The method suggested by moyeradon could be paired with another refactor as well

value = calculate(shop.flavor_value(flavor))

with Shop having a method that now handles the flavors

def flavor_value(flavor)
  flavor_sym = flavor.downcase.to_sym

  # Then call the desired logic to get the values being returned by the straw, chocolate, van, man methods here
end

This way Icecream doesn't know about individual flavors and as the flavors change you don't need to update Icecream.

CodePudding user response:

I would do thow things: Extract code into a helper method and using a hash instead of the case block:

FLAVORS = { 
  'STRAWBERRY' => :straw, 'CHOCOLATE' => :choc, 'VANILLA' => :van, 'MANGO' => :man 
}.freeze

def do_math(flavor)
  (flavor * 1000).round(5)
end

with those two preparations you can set the value like this:

value = do_math(shop.public_send(FLAVORS[flavors]))
  • Related