Skip to content

Instantly share code, notes, and snippets.

@shunsugai
Last active December 11, 2015 08:09
Show Gist options
  • Save shunsugai/4571659 to your computer and use it in GitHub Desktop.
Save shunsugai/4571659 to your computer and use it in GitHub Desktop.
#かなり雑だけどこんな書き方もできる
class Bar
def initialize(options={})
@options = options
end
def method_missing(name, *args)
if name =~ /=$/
@options[name.to_s.chop.to_sym] = args.first
else
@options[name.to_sym]
end
end
end
bar = Bar.new(:name => 'Hoge')
p bar.name #=> Hoge
bar.name = 'Mark'
p bar.name #=> Mark
# define_methodを使った例
class Foo
def initialize(options={})
@options = options
@options.each_key {|key| Foo.define(key)}
end
def self.define(name)
define_method(name) do
@options[name]
end
define_method("#{name}=") do |arg|
@options[name] = arg
end
end
end
foo = Foo.new(:name => "original value")
puts foo.name #=> original value
foo.name = "Mark"
puts foo.name #=> Mark
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment