Vincent
Vincent

Reputation: 4056

Ruby use method only if condition is true

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?

Upvotes: 0

Views: 1976

Answers (4)

Vojto
Vojto

Reputation: 6959

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.

Upvotes: 0

robertokl
robertokl

Reputation: 1909

def info(arg = nil)
  info = {"width" => @width,
          "height" => @height,
          "color" => @color}
  info[arg] || info
end

Upvotes: 5

Sniggerfardimungus
Sniggerfardimungus

Reputation: 11782

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

Upvotes: -1

user130532
user130532

Reputation:

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

that should steer you in the right direction.

Upvotes: 0

Related Questions