Skip to content

Instantly share code, notes, and snippets.

@meltedice
Created September 5, 2016 02:32
Show Gist options
  • Save meltedice/b958d141d173e99e0ff91658cbd552d1 to your computer and use it in GitHub Desktop.
Save meltedice/b958d141d173e99e0ff91658cbd552d1 to your computer and use it in GitHub Desktop.
How to pass value to a class that generated by Class.new in ruby
# How to pass value to a class that generated by Class.new in ruby
# ruby で Class.new で生成した class に値を渡す方法
def ClassTemplate(name)
Class.new do |klass|
klass.instance_variable_set :@my_name, name
def hello
puts "Hello, #{self.class.instance_variable_get(:@my_name)}!"
end
end
end
klass1 = ClassTemplate("Jack")
klass2 = ClassTemplate("Taro")
klass1.new.hello # => Hello, Jack!
klass2.new.hello # => Hello, Taro!
klass1.new.hello # => Hello, Jack!
klass2.new.hello # => Hello, Taro!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment