Last active
December 11, 2015 08:09
-
-
Save shunsugai/4571659 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#かなり雑だけどこんな書き方もできる | |
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