|
|
IronRuby > Documentation > .NET Integration > Classes
ClassesFrom $1Table of contents
Classes are the main encapsulation structure for the CLR, and IronRuby treats them as Ruby classes. p = Person.new("Jimmy")
#=> Models.Person This allows you to use any .NET framework classes from IronRuby. dict = System::Collections::Generic::Dictionary[String, Array].new #=> System.Collections.Generic.Dictionary`2[IronRuby.Builtins.MutableString,IronRuby.Builtins.RubyArray] dict['foo'] = [1,2,3] #=> [1, 2, 3] dict[23] = '34' #:0: can't convert String into Array (TypeError) # dict[23] = [4,5,6] #:0: can't convert Fixnum into String (TypeError) # dict['bar'] = [4,5,6] #=> [4, 5, 6] Find more about using .NET framework classes in IronRuby. InheritanceJust like Ruby classes, .NET classes can be sub-classed in IronRuby. class MyPerson < Models::Person
attr_reader :age
def self.new(name, age)
instance = super(name)
instance.instance_variable_set(:"@age", age)
instance
end
end
#=> nil
p = MyPerson.new('jimmy', 25)
#=> <MyPerson:0x0000060 @age="25"> ReopeningTo a Ruby programmer, creating a subclass just to add a field seems like overkill, and they’d want to simply add the field to the existing Person class. class Models::Person
attr_reader :age
class << self
alias super_new new
def new(name, age)
instance = super_new(name)
instance.instance_variable_set(:"@age", age)
instance
end
end
end
#=> nil
Person.new("Jimmy", 25)
#=> <Models::Person:0x000005c @age="25">
Tags:
|