发布于 2016-01-24 04:13:28 | 139 次阅读 | 评论: 0 | 来源: 网友投递
Ruby编程语言
Ruby,一种为简单快捷的面向对象编程(面向对象程序设计)而创的脚本语言,在20世纪90年代由日本人松本行弘开发,遵守GPL协议和Ruby License。它的灵感与特性来自于 Perl、Smalltalk、Eiffel、Ada以及 Lisp 语言。
今天被问到此类问题,以前总是觉得这个是比较宽泛的一个概念,自己即使是用过这些特性,但却一直不知道这叫“元编程” 直到今天被人问起的时候,方才顿悟一些,随后便在网上和自己的平实用的一些元编程做个小总结。
原来所谓的Ruby中的元编程,是可以在运行时动态的操作语言结构(如类、模块、实例变量等)的技术。你甚至于可以在不用重启的情况下,在运行时直接键入一段新的Ruby代码,并执行他。
Ruby的元编程,也具有“利用代码来编写代码”的作用。例如,常见的attr_accessor等方法就是如此。
首先我能想到的自己用过的有这么几个:
1,respond_to?
2,define_method
3,instance_variable_get, instance_variable_set
4,eval 不过这个方法能尽量避免就避免,执行效率特别低!!
具体的意思想必一看方法名字 就知道这些方法的所要实现的逻辑。
具体可详见http://api.rubyonrails.org/ 上具体分析源码,很简单。
以下是我从其他地方搜索而来,以便以后的工作中有助于提高自己的编程技能;
1,内省,反射
在Ruby中,你完全有能力在运行时查看类或对象的信息。我们可以使用class、 instance_methods、 intance_variables等方法来达到目的。我们讲这种技术成为内省(Introspection)或者反射(Reflection)。
一说编写元程序的语言称之为元语言。被操纵的程序的语言称之为目标语言。一门编程语言同时也是自身的元语言的能力称之为反射或者自反。 ——摘自维基百科元编程条目。
classRubyist
defwhat_does_he_do
@person='A Rubyist'
'Ruby programming'
end
end
an_object = Rubyist.new
puts an_object.class# => Rubyist
puts an_object.class.instance_methods(false)# => what_does_he_do
an_object.what_does_he_do
puts an_object.instance_variables# => @person
classRubyist
definitialize
@geek="Matz"
end
end
obj = Rubyist.new
# instance_eval可以操纵obj的私有方法以及实例变量
obj.instance_evaldo
putsself# => #puts@geek# => Matz
end
classRubyist
end
Rubyist.instance_evaldo
defwho
"Geek"
end
end
puts Rubyist.who# => Geek
const_get, const_set
puts Float.const_get(:MIN)# => 2.2250738585072e-308
classRubyist
end
puts Rubyist.const_set("PI",22.0/7.0)# => 3.14285714285714
# Let us call our new class 'Rubyist'
# (we could have prompted the user for a class name)
class_name ="rubyist".capitalize
Object.const_set(class_name,Class.new)
# Let us create a method 'who'
# (we could have prompted the user for a method name)
class_name =Object.const_get(class_name)
puts class_name# => Rubyist
class_name.class_evaldo
define_method:whodo|my_arg|
my_arg
end
end
obj = class_name.new
puts obj.who('Matz')# => Matz