赞 | 13 |
VIP | 118 |
好人卡 | 28 |
积分 | 12 |
经验 | 35779 |
最后登录 | 2017-7-6 |
在线时间 | 1564 小时 |
Lv3.寻梦者
- 梦石
- 0
- 星屑
- 1170
- 在线时间
- 1564 小时
- 注册时间
- 2008-7-30
- 帖子
- 4418

|
本帖最后由 DeathKing 于 2011-2-10 10:50 编辑
New Ruby 1.9 Features, Tips & Tricks: http://www.igvita.com/2011/02/03 ... atures-tips-tricks/
补一些重要的翻译
* Ruby 1.9.X Oniguruma作为新的正则式引擎。(关于Oniguruma引擎的特性,请看之前紫苏的相关介绍);
* Ruby 1.9.X 允许带有默认值的参数放在前面了。- def f(a=1, b); p [a,b]; end;
- p f(2) # => [1, 2]
复制代码 * Ruby 1.9.X 默认使用 Object#inspect 来代替to_s;- puts({a:1, b:[2,3]}.to_s) # => {:a=>1, :b=>[2, 3]}
复制代码 * Ruby 1.9.X 加入了一个 Hash#assoc 方法,返回 [key, hsh[key]]- p({a: 1, b: 2}.assoc(:b)) # => [:b, 2]
复制代码 * Ruby 1.9.X 允许你把可变参数放在参数列表的任何位置;- def a(a,*b,c); p [a,b,c]; end
- p a(1,2,3,4) # => [1, [2, 3], 4]
复制代码 * Ruby 1.9.X 能对符号使用正则式了;- p :ruby_symbol.match(/symbol/) # => 5
复制代码 * Ruby 1.9.X 提供了一种新的建立Hash的方法,这种方法更加紧凑;- p({a:1, b:2}) # => {:a=>1, :b=>2}
复制代码 * Ruby 1.9.X 提供了一种建立 stabby proc 的方法(个人认为类似于lambda表达式?);- f = -> a,b { p [a,b] }
- p f.call(1,2) # => [1, 2]
复制代码 * Ruby 1.9.X 的 Hash 已经有序了;(可以参见之前的讨论)- p({a:1, b:2}) # => {:a=>1, :b=>2}
复制代码 * Ruby 1.9.X 提供了4种调用Proc的方法;- f =->n {[:hello, n]}
- p f[:ruby] # => [:hello, :ruby]
- p f.call(:ruby) # => [:hello, :ruby]
- p f.(:ruby) # => [:hello, :ruby]
- p f === :ruby # => [:hello, :ruby]
复制代码 * Ruby 1.9.X 不再支持 String#each 方法了,请使用chars,bytes,lines,each_char等(个人猜测是因为each容易引起歧义?);
* Ruby 1.9.X 添加了 Enumerable#sample(n) 方法,随机抽出 n 个元素(个人认为是模拟抽样);- p [1,2,3,4].sample(2) # => [2, 3]
复制代码 * Ruby 1.9.X 添加了Kernel#define_singleton_method 函数,以后定义单例可以这样做:- c = 'cat'; c.define_singleton_method(:hi) { p 'hi' };
- p c.hi # => "hi"
复制代码 * Ruby 1.9.X 提供了能创建生命周期只在块中的临时变量;- v = 'ruby'; [1,9].map {|val; v| v = val }
- p v # => "ruby"
复制代码 * Ruby 1.9.X 允许块使用块作为参数了;- b = -> v, &blk { p [v, blk.call] }
- p b.call(:a) { :b } # => [:a, :b]
复制代码 * Ruby 1.9.X 将线程映射到 OS 的线程上;(订正请求:"Ruby 1.9 threads are now mapped (1:1) to OS threads! ex: gdb -p [ruby PID], info threads - yes, there is still a GIL.")
* Ruby 1.9.X 加入了新的垃圾回收方法,GC.count和GC::Profiler;- GC::Profiler.enable; GC.start; puts GC::Profiler.result
复制代码 * Ruby 1.9.X 允许你内观 Ruby 虚拟机 YARV 编译好的字节码;- puts RubyVM::InstructionSequence.compile('a = 1; p 1 + a').disassemble
复制代码 |
|