|
Space Map
|
Meta Programming이란?
Built In MetaProgramming
attr_reader :id, :age attr_writer :name attr_accessor :color attr_readerclass Module
def attr_reader (*syms)
syms.each do |sym|
class_eval %{def #{sym}
@#{sym}
end}
end
end
end
attr_writerclass Module
def attr_writer (*syms)
syms.each do |sym|
class_eval %{def #{sym}= (val)
@#{sym} = val
end}
end
end
end
Reflection자바의 Reflection과 같은 기능을 Ruby에서도 가지고 있으며, 이를 Reflection이라고 칭한다. 그러나 Ruby가 가지는 Reflection은 자바 그 이상이다. Ruby의 Reflection을 통하여 할 수 있는 작업
Looking at Objectsa = 102.7
b = 95.1
ObjectSpace.each_object(Numeric) { |x| p x }
result 95.1 102.7 2.71828182845905 3.14159265358979 2.22044604925031e-16 1.79769313486232e+308 2.2250738585072e-308 Looking Inside Objectsr = 1..10 #Create a Range Object
list = r.methods
p list.length
p list[0..3]
result 68 ["collect", "inspect", "send", "all?"] 위 예제에서 보는 바와 같이 모든 Object는 그 자신에 대한 Object 정보에 접근할 수 있는 메써드를 제공한다. 또한 다음과 같은 방법으로 특정 메써드가 존재하는지의 여부를 체크하는 것이 가능하다. r = "you" r.respond_to?("frozen?") => true r.respond_to?(:has_key?) => false "me".respond_to?("==") => true Object 정보를 얻어낼 수 있는 다양한 방법 num = 1 p num.object_id => 3 p num.class => Fixnum p num.kind_of?(Fixnum) => true p num.kind_of?(Numeric) => true p num.instance_of?(Fixnum) => true p num.instance_of?(Numeric) => false
Looking at Classes참고 문헌
|
|