How to implement options hashes in Ruby?

后端 未结 4 1279
离开以前
离开以前 2021-02-06 14:47

How can I implement options hashes? How is the structure of a class that has option hashes in it? Say I have a person class. I want to implement a method such as my_age that whe

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-06 15:45

    You could do something like this:

    class Person
    
      def initialize(opts = {})
        @options = opts
      end
    
      def my_age
        return @options[:age] if @options.has_key?(:age)
      end
    
    end
    

    and now you're able to call to the age like this

    p1 = Person.new(:age => 24)
    p2 = Person.new p1.my_age # => 24
    p2.my_age # => nil

提交回复
热议问题