What's the nature of “property” in a Ruby class?

前端 未结 3 1782
攒了一身酷
攒了一身酷 2021-01-19 02:00

I don\'t understand the keywords like attr_reader or property in the following example:

class Voiture 
  attr_reader :name
  attr_         


        
3条回答
  •  半阙折子戏
    2021-01-19 02:53

    You will want to monkey patch the class Module. That's where methods like attr_reader reside.

    class Module
      def magic(args)
         puts args.inspect
      end
    end
    
    class A
      magic :hello, :hi
    end
    #=> [:hello, :hi]
    

    As The Tin Man mentioned, monkey-patching base-level classes can be dangerous. Consider it like time-traveling into the past and adding something in the past. Just make sure that what you are adding isn't going to overwrite some other event or else you could come back to a Ruby script/timeline that isn't the same one you left.

提交回复
热议问题