So I have this code:
class Door
# ...
def info a开发者_运维百科ttr = ""
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
The method "info" should return the hash if no argument is provided, otherwise the value of the argument in the hash. How can I achieve that?
def info(arg = nil)
info = {"width" => @width,
"height" => @height,
"color" => @color}
info[arg] || info
end
def info (arg1 = @width, arg2 = @height, arg3 = @color)
"#{arg1}, #{arg2}, #{arg3}."
end
that should steer you in the right direction.
If you want to return instance variable specified in argument, you can try this:
def info(atr=nil)
[:a, :b, :c].include?(atr.to_sym) ? instance_variable_get(atr) : nil
end
This return instance variable if it is contained in [:a, :b, :c]
array. That's for security reasons, you don't want to return any instance variable.
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
精彩评论