我想在不同的方法中添加从用户输入声明的变量的值,以便如何对来自不同方法(如sum=a+c+d
)的结果的所有变量值求和,并根据总和声明一些语句。
class Mets
attr_accessor :wp
attr_accessor :hdl
attr_accessor :tc
def initialize(wp,hdl,tc)
@wp = wp`enter code `
@hdl = hdl
@tc = tc
end
`
#type the wp number within the ranges and enter it will return "a" value pertaining to that range
print"what is the wp?"
wp=gets.to_i
case wp
when 95..100 then print "a=1\n"
when 101..102 then print "a=2\n"
when 103..110 then print "a=3\n"
when 111..120 then print "a=4\n"
when 121..130 then print "a=5\n"
end
#type the hdl number within the ranges and enter it will return "a" value pertaining to that range
print"what is the hdl?"
hdl=gets.to_i
case hdl
when 40..49 then print "c=1\n"
when 10..39 then print "c=3\n"
end
#type the tc number within the ranges and enter it will return "a" value pertaining to that range
print "what is the tc?"
tc=gets.to_i
case tc
when 160..199 then print "d=2\n"
when 200..239 then print "d=4\n"
when 240..279 then print "d=5\n"
when 280..500 then print "d=6\n"
end
end
#output: you see values of a,c,d printing pertaining to that ranges,now i want to add all this variables(a,c,d) declared after user inputs ?please suggest what has to be done
答案 0 :(得分:1)
class Mets
attr_accessor :wp
attr_accessor :hdl
attr_accessor :tc
def initialize(wp, hdl, tc)
@wp = wp # `enter code `
@hdl = hdl
@tc = tc
end
def total
@wp + @hdl + @tc
end
end
total = Mets.new(2, 3, 5).total
puts "The total is: #{total}"
这就是你要添加实例变量的方法。
如果你想利用你的attr_accessors,你可以这样做:
def total
wp + hdl + tc
end
希望有所帮助。
答案 1 :(得分:1)
我将您的问题解释为仅询问如何最好地整理代码。 (说实话,我正在考虑如何处理更一般的案例。)这是一种方法。关键是Mets类中的最后一个方法,它为后面的每个标记类提供一个“钩子”。要更改,删除或添加令牌,只需修改,删除或添加适用的子类。请注意,数组@subclasses
是一个类实例变量。我假设您想要的只是您提到的值的总和。如果我误解了,应该很容易修改代码以满足您的要求。它可能包含错误。
class Mets
class << self
attr_reader :subclasses
end
@subclasses = []
def self.calc_sum
Mets.subclasses.inject do |t, subclass|
sci = subclass.new
print "What is the #{sci.token}? "
t + sci.response(gets.to_i) # Have not worried about out-of-range entries
end
end
def self.inherited(subclass)
Mets.subclasses << subclass
end
end
class Mets_wp < Mets
def token() 'wp' end
def response(val)
case val
when 95..100 then 1
when 101..102 then 2
when 103..110 then 3
when 111..120 then 4
when 121..130 then 5
end
end
end
class Mets_hdl < Mets
def token() 'hdl' end
def response(val)
case val
when 10..39 then 3
when 40..49 then 1
end
end
end
...and so on
Mets.calc_sum