Ruby Ruby 2.2 新方法一览

juanito · 2014年12月28日 · 最后由 debugger 回复于 2014年12月30日 · 4542 次阅读

原文:Ruby 2.2 New Methods by Example 相关帖子:Ruby 2.2 Tips: max (n), max_by (n), min (n), min_by (n) | Ruby China

Object

Object#itself

http://www.ruby-doc.org/core-2.2.0/Object.html#method-i-itself

返回对象自身。

> 3.itself
=> 3

Method

Method#super_method

http://www.ruby-doc.org/core-2.2.0/Method.html#method-i-super_method

class People
  def greeting
    'Salve'
  end
end

class American < People
  def greeting
    'Hello'
  end
end
> american = American.new
=> #<American:0x007febbe300ff0>

> american.public_method(:greeting).super_method.call
=> 'Salve'

Enumerable

Enumerable#slice_after

http://ruby-doc.org/core-2.2.0/Enumerable.html#method-i-slice_after

> pi = Math::PI.to_s.scan(/\d/).map(&:to_i)
=> [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3]

> pi.slice_after(&:even?).to_a
=> [[3, 1, 4], [1, 5, 9, 2], [6], [5, 3, 5, 8], [9, 7, 9, 3]]

Enumerable#slice_when

http://ruby-doc.org/core-2.2.0/Enumerable.html#method-i-slice_when

> pi = Math::PI.to_s.scan(/\d/).map(&:to_i)
=> [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 8, 9, 7, 9, 3]

> pi.slice_when { |a, b| a.even? && b.odd? }.to_a
=> => [[3, 1, 4], [1, 5, 9, 2, 6], [5, 3, 5, 8], [9, 7, 9, 3]]

maxmax_byminmin_by these methods accept a argument n, n is how many max (min) numbers you wanna return.

Enumerable#max

http://ruby-doc.org/core-2.2.0/Enumerable.html#method-i-max

> [*1..10].max 2
=> [10, 9]

Enumerable#min

http://ruby-doc.org/core-2.2.0/Enumerable.html#method-i-min

> [*1..10].min 2
=> [1, 2]

Enumerable#max_by

http://ruby-doc.org/core-2.2.0/Enumerable.html#method-i-max_by

> %w[a aa aaa].max_by 2, &:length
=> ["aaa", "aa"]

Enumerable#min_by

http://ruby-doc.org/core-2.2.0/Enumerable.html#method-i-min_by

> %w[a aa aaa].min_by 2, &:length
=> ["a", "aa"]

Float

Float#next_float

http://www.ruby-doc.org/core-2.2.0/Float.html#method-i-next_float

Return next float.

> 3.1415926.next_float
=> 3.1415926000000005

Float#prev_float

http://www.ruby-doc.org/core-2.2.0/Float.html#method-i-prev_float

Return previous float.

> 3.1415926.prev_float
=> 3.1415925999999996

File

File.birthtime

http://www.ruby-doc.org/core-2.2.0/File.html#method-c-birthtime

> File.birthtime 'README.md'
=> 2014-10-04 13:40:29 +0800

File#birthtime

http://www.ruby-doc.org/core-2.2.0/File.html#method-c-birthtime

> File.open('README.md') { |file| file.birthtime }
=> 2014-10-04 13:40:29 +0800

String

String.unicode_normalizeString.unicode_normalize!String.unicode_normalize?

对字串进行 Unicode 正规化。

> bad = "¿como\u0301 esta\u0301s?"
=> "¿comó estás?"

> p bad.unicode_normalize
=> "¿comó estás?"

> p bad
=> "¿comó estás?"

> p bad.unicode_normalized?
=> false

> p bad.unicode_normalize!
=> "¿comó estás?"

> p bad
=> "¿comó estás?"

> p bad.unicode_normalized?
=> true

感觉越来越花哨了

看那几个 Enum 的函数,很有函数式的感觉

加入Object#itself的意义是什么……

嗯,无脑学习了解,thx

需要 登录 后方可回复, 如果你还没有账号请 注册新账号