2012-05-24 43 views
-1
class Airplane 
    attr_reader :weight, :aircraft_type 
    attr_accessor :speed, :altitude, :course 

    def initialize(aircraft_type, options = {}) 
    @aircraft_type = aircraft_type.to_s 
    @course = options[:course.to_s + "%"] || rand(1...360).to_s + "%" 
    end 

如何在1到360之间使用initialize中散列的最小和最大允许值?用于初始化散列的最小值和最大值

例子:

airplane1 = Airplane.new("Boeing 74", course: 200) 
p radar1.airplanes 
=> [#<Airplane:0x000000023dfc78 @aircraft_type="Boeing 74", @course="200%"] 

但如果我设置为当然值370,airplane1不应该工作

+1

你的问题不是很清楚。什么是“允许”值?你指的是什么哈希?你期望什么样的散列的最终值得到某些输入? –

+1

好的,所以你想确保'options [:course]'在一个指定的值范围内?如果不是,会发生什么? (“不工作”不是很清楚。) –

+0

是的,我想要:具有指定数值范围的课程,如果不是 - 会自动插入最大值 – Savroff

回答

1

这可重构我敢肯定,但是这是我想出了

class Plane 

    attr_reader :weight, :aircraft_type 
    attr_accessor :speed, :altitude, :course 

    def initialize(aircraft_type, options = {}) 
    @aircraft_type = aircraft_type.to_s 
    @course = options[:course] || random_course 
    check_course 
    end 

    def check_course 
    if @course < 1 or @course > 360 
     @course = 1 
     puts "Invalid course. Set min" 
    elsif @course > 360 
     @course = 360 
     puts "Invalid course. Set max" 
    else 
     @course = @course 
    end 
    end 

    def random_course 
    @course = rand(1..360) 
    end 

end 
+0

适合我吗?不知道 – Tallboy

+1

'rand'理解一个'Range'参数是一个1.9.3不在1.9.2中的东西。 PS:如果你最终使用随机课程,你会把你的'%'符号加倍,不是吗? –

1

我想你的意思是你不想让人们在类似{course: '9000%'}传为options和如果它是无效的,你想错误。如果是这样的话,你可以测试它是否在范围:

def initialize(aircraft_type, options = {}) 
    @aircraft_type = aircraft_type.to_s 
    allowed_range = 1...360 
    passed_course = options[:course] 
    @course = case passed_course 
    when nil 
     "#{rand allowed_range}%" 
    when allowed_range 
     "#{passed_course}%" 
    else 
     raise ArgumentError, "Invalid course: #{passed_course}" 
    end 
end 
+0

哪个版本的“rand”知道如何处理Range?引发ArgumentError可能比RuntimeError更好。 –

+0

@ muistooshort:1.9.3'rand'支持范围。我很确定它在该版本中是新的。由于OP使用它,我认为这是一个安全的假设,以使他的Ruby是最新的。你对错误类型是正确的。感谢那。 – Chuck

+1

是的,这是一个1.9.3的东西,我使用的是1.9.2。这将我每个人不RTFM。 –

1

course是一个角度,ISN是吗?它不应该是0...360它的有效范围吗?为什么最后的“%”?以及为什么要使用字符串而不是整数?

无论如何,这就是我想要写:

@course = ((options[:course] || rand(360)) % 360).to_s + "%"