Ruby: methods as array elements - how do they work?

前端 未结 6 1822
一向
一向 2021-02-19 05:58

This probably isn\'t something you should try at home, but for some reason or another I tried to create an array of methods in Ruby.

I started by defining two methods.

6条回答
  •  遥遥无期
    2021-02-19 06:44

    Here's my two-pennies worth. Building on the solutions already posted, this is an example of a working example. What might be handy for some here is that it includes method arguments and the use of self (which refers to the instance of the PromotionalRules class when it is instantiated) and the array of symbols, which is neat - I got that from the Ruby docs on the #send method here. Hope this helps someone!

    class PromotionalRules
      PROMOTIONS = [:lavender_heart_promotion, :ten_percent_discount]
    
      def apply_promotions total, basket
        @total = total
    
        if PROMOTIONS.count > 0
          PROMOTIONS.each { |promotion| @total = self.send promotion, @total, basket }
        end
    
        @total.round(2)
      end
    
      def lavender_heart_promotion total, basket
        if two_or_more_lavender_hearts? basket
          basket.map { |item| total -= 0.75 if item == 001 }
        end
        total
      end
    
      def two_or_more_lavender_hearts? basket
        n = 0
        basket.each do |item|
          n += 1 if item == 001
        end
        n >= 2
      end
    
      def ten_percent_discount total, *arg
        if total > 60.00
          total = total - total/10
        end
        total
      end
    end
    

    Thanks to everyone for their help. I love the open-source nature of coding - threads just get better and better as people iterate over each other's solutions!

提交回复
热议问题