tags:

views:

83

answers:

4

So I have this code:

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

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?

A: 
def info (arg1 = @width, arg2 = @height, arg3 = @color)
  "#{arg1}, #{arg2}, #{arg3}."
end

that should steer you in the right direction.

predhme
A: 
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
+4  A: 
def info(arg = nil)
  info = {"width" => @width,
          "height" => @height,
          "color" => @color}
  info[arg] || info
end
robertokl
Nice idea. Is there any possibility to do it without a variable?
Vincent
It is, but AFAIK it has to be hackish: `{"width"=>@width, "height"=>@height, "color"=>@color}.send(*(arg ? [:[], arg] : [:to_hash]))`
Mladen Jablanović
I love hackish ;)
Vincent
A: 

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.

Vojto