-3

我想在不同的方法中添加从用户输入声明的变量的值,以便如何对来自不同方法的所有变量值求和,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
4

2 回答 2

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

希望有帮助。

于 2013-09-12T03:17:03.750 回答
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
于 2013-09-12T04:57:37.613 回答