gpt4 book ai didi

ruby-on-rails - 如何摆脱 if 语句

转载 作者:太空宇宙 更新时间:2023-11-03 18:15:06 24 4
gpt4 key购买 nike

这是 bmr 的假实现我在我的 Ruby on Rails 应用程序中使用的计算。

由于公式仅使用公制单位,如果英制单位被设置为用户的默认值,我必须以某种方式将英制单位转换为公制。

我想出了这段代码。

个人觉得这种小问题的代码很多。相反,使用多态性将过度工程化。改进此代码的方法?

require 'ostruct'
require 'delegate'

module BmrCalculator
class Calculator
def call(sex = :male, measurement_unit = :metric)
user = OpenStruct.new(sex: sex, weight: 2, height: 2, measurement_unit: measurement_unit)

if measurement_unit == :imperial #dont like it
user = ImperialToMetricDecorator.new(user)
end

BmrCalculator.new.bmr(user)
end

class BmrCalculator
def bmr(user)
if user.sex == :male
puts user.inspect
puts 1 * user.weight + 2 * user.height + 3 #this formula works only with metric units
else
puts user.inspect
puts 6 * user.weight + 3 * user.height + 5 #this formula works only with metric units
end
end
end
end

class ImperialToMetricDecorator < SimpleDelegator
def height
(super * 2.54)
end

def weight
(super / 2.2)
end
end

Calculator.new.call(:male, :metric)
end

最佳答案

您可以通过使用 OOP 和创建有意义的表示来改进您的代码:

class Length < Float
end

class Feet < Length
def to_meters
..
end
end

class Meters < Length
def to_feet
..
end
end

class Gender < Object
end

class Male < Gender
def bmr(weight)
...
end
end


class Female < Gender
def bmr(weight)
...
end
end

这可能看起来像更多的代码,但实际上更容易阅读、测试和维护。

关于ruby-on-rails - 如何摆脱 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27661583/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com