Last active
February 2, 2020 16:34
-
-
Save shrkw/f8f171fae89482860ccaaa22ec6452e0 to your computer and use it in GitHub Desktop.
RubyでScalaのケースクラスっぽいことがしたかったのでStructを使えばよかった ref: https://qiita.com/shrkw/items/79772b6691f1aee94570
This file contains 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 Food | |
attr_reader :price, :name | |
def initialize(price, name) | |
@price = price | |
@name = name | |
end | |
end |
This file contains 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 Food | |
attr_reader :price, :name | |
def initialize(price, name) | |
@price = price | |
@name = name | |
end | |
end |
This file contains 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
def case_class(*args) | |
claz = Class.new | |
claz.send :define_method, :initialize, Proc.new do |*iargs| | |
args.each_with_index do |arg, idx| | |
self.instance_variable_set("@#{arg}", iargs[idx]) | |
end | |
end | |
args.each do |arg| | |
claz.send :define_method, arg, Proc.new do | |
self.instance_variable_get("@#{arg}") | |
end | |
end | |
claz | |
end |
This file contains 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
def case_class(*args) | |
claz = Class.new | |
claz.send :define_method, :initialize, Proc.new do |*iargs| | |
args.each_with_index do |arg, idx| | |
self.instance_variable_set("@#{arg}", iargs[idx]) | |
end | |
end | |
args.each do |arg| | |
claz.send :define_method, arg, Proc.new do | |
self.instance_variable_get("@#{arg}") | |
end | |
end | |
claz | |
end |
This file contains 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
[161] pry(main)> Person = case_class :name, :age | |
=> Person | |
[162] pry(main)> p1 = Person.new('Adam', 30) | |
=> #<Person:0x007fdec619be80 @age=30, @name="Adam"> | |
[163] pry(main)> p2 = Person.new('Bob', 14) | |
=> #<Person:0x007fdec53c29d0 @age=14, @name="Bob"> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment