Initialize a Ruby class from an arbitrary hash, but only keys with matching accessors

后端 未结 6 594
遇见更好的自我
遇见更好的自我 2021-01-01 04:00

Is there a simple way to list the accessors/readers that have been set in a Ruby Class?

class Test
  attr_reader :one, :two

  def initialize
    # Do someth         


        
6条回答
  •  不思量自难忘°
    2021-01-01 04:41

    You can look to see what methods are defined (with Object#methods), and from those identify the setters (the last character of those is =), but there's no 100% sure way to know that those methods weren't implemented in a non-obvious way that involves different instance variables.

    Nevertheless Foo.new.methods.grep(/=$/) will give you a printable list of property setters. Or, since you have a hash already, you can try:

    def initialize(opts)
      opts.each do |opt,val|
        instance_variable_set("@#{opt}", val.to_s) if respond_to? "#{opt}="
      end
    end
    

提交回复
热议问题