Ruby/Class/object Creation
Материал из Wiki.crossplatform.ru
Add private method to Object and call it in instance class
class Object private def set_instance_variables(binding, *variables) variables.each do |var| eval("@#{var} = #{var}", binding) end #instance_variable_set("@#{var}", var) end end class RGBColor def initialize(red=0, green=0, blue=0) set_instance_variables(binding, *local_variables) end end RGBColor.new(10, 200, 300) # => #<RGBColor:0xb7c22fc8 @red=10, @blue=300, @green=200>
Alias method name
class Object def in(other) other.include? self end end x = [1, 2, 3] if 2.in x puts "yes" # Prints "yes" else puts "no" end
Creating an Object
# You use the new method to create an object in Ruby. class Animal def initialize @color = "red" end def get_color return @color end end animal = Animal.new