当尝试使用单个参数创建一个类时,我收到以下错误:NameError:未定义的局部变量或方法radius' for #<Circle:0x007fdcda2b75c8> from circle_constructor.rb:13:in
初始化&#39;
class Circle
def initialize(circle_constructor = {})
circle_constructor = {@radius => radius, @diameter => diameter}
@radius = radius
@diameter = diameter
end
end
答案 0 :(得分:1)
如果我理解正确,您尝试使用您获得的哈希作为参数初始化@radius
和@diameter
,请尝试以下操作:
class Circle
def initialize(circle_constructor = {})
## circle_constructor = {@radius => radius, @diameter => diameter}
## you are inserting wrongly values to local variable inside constractor wothout doing nothing with it so remove it or do this:
## @circle_constructor = { radius: radius, diameter: diameter }
## make sure you populate radius and diameter local variables before.
@radius = circle_constructor[:radius]
@diameter = circle_constructor[:diameter]
end
end
答案 1 :(得分:0)
Ruby不支持开箱即用,但您可以使用Hashie库。它有几个散列变体,破折号适用于此。
require 'hashie/dash'
class Circle < Hashie::Dash
property :radius, required: true
property :diameter, required: true
end
# USAGE
Circle.new(radius: 10, diameter: 5)
(侧面说明,你的圆圈同时接受半径和直径是奇怪的。除非是用户输入,例如测验,你应该能够从另一个中导出一个,所以它通常只有一个构造函数param和另一个将是一种方法。)