所以我有这段代码:
class Door
# ...
def info attr = ""
return {
"width" => @width,
"height" => @height,
"color" => @color
}[attr] if attr != ""
end
end
mydoor = Door.new(100, 100, "red")
puts mydoor.info("width")
puts mydoor.info
如果没有提供参数,方法“info”应返回散列,否则返回散列中参数的值。我怎样才能做到这一点?
答案 0 :(得分:5)
def info(arg = nil)
info = {"width" => @width,
"height" => @height,
"color" => @color}
info[arg] || info
end
答案 1 :(得分:0)
def info (arg1 = @width, arg2 = @height, arg3 = @color)
"#{arg1}, #{arg2}, #{arg3}."
end
应该引导你朝着正确的方向前进。
答案 2 :(得分:0)
如果要返回参数中指定的实例变量,可以尝试:
def info(atr=nil)
[:a, :b, :c].include?(atr.to_sym) ? instance_variable_get(atr) : nil
end
如果它包含在[:a, :b, :c]
数组中,则返回此实例变量。这是出于安全原因,您不希望返回任何实例变量。
答案 3 :(得分:-1)
def info(attr="")
case attr
when "width" then return @width
when "height" then return @height
when "color" then return @color
else return {"width"=>@width, "height"=>@height, "color"=>@color}
end
end