自Ruby 2.1.0起, Ruby核心團隊每年聖誕節都發布了新版本的Ruby, 這次我們得到了2.7.0。 這可能是Ruby的最新2.x版本, 因爲Ruby 3.0有望在明年聖誕節發佈。
這是一個簡短的摘要 此發行版中一些最有趣的函數。 (有關以前的版本,請參閱: 2.6 , 2.5 , 2.4 , 2.3 )。
模式匹配
引入了新的模式匹配語法, 它允許您編寫如下的case語句:
def test_pattern(value)
case value
in 0
'Zero'
in Integer if value < 0
'Negative'
in Integer => n
"Number #{n}"
in { value: x }
"Hash value: #{x}"
in _
'Unknown'
end
end
test_pattern(-1) #=> 'Negative'
test_pattern(0) #=> 'Zero'
test_pattern(2) #=> 'Number: 2'
test_pattern({ value: 3 }) #=> 'Hash value: 3'
test_pattern('four') #=> 'Unknown'
無起點範圍
在2.6中,我們獲得了無限範圍, 這次我們將有無起點的範圍。 這將允許使用如下語法:
case n
when ..0 then 'Negative'
when 1..9 then 'Single digit'
when 10.. then 'Two or more'
end
另一個有趣的用途 將是在DSL中使用此函數的能力。 例如, 我們可以在ActiveRecord中做到這一點:
Task.where(due_on: ..Date.today)
編號參數
添加了新語法 將編號的參數添加到塊中。
(1..3).map { _1 * _1 } #=> [1, 4, 9]
hash = { a: 2, b: 3 }
hash.map { "#{_1} = #{_2}" } #=> ["a = 1", "b = 2"]
add_3 = -> { _1 + _2 + _3 }
add_3.call(3, 5, 7) #=> 15
這些是人爲的例子, 但到目前爲止,我還不認爲值得添加這種新語法, 而且我看不出自己在明確的論點上使用了它。
新枚舉和數組方法
Enumerable#tally
計算一個枚舉中每個項目的出現, 並將其作爲哈希值返回。
strings = ['a', 'a', 'a', 'b', 'c']
strings.tally
#=> { 'a' => 3, 'b' => 1, 'c' => 1 }
# in 2.6, we'd do it like this:
strings.each_with_object({}) do |value, result|
result[value] ||= 0
result[value] += 1
end
Enumerable#filter_map
結合了select
和map
合併爲一個塊, 避免了中間數組分配的需要。
# squares of odd numbers in 1..10
(1..10).filter_map { |x| x*x if x.odd? } #=> [1, 9, 25, 49, 81]
# ruby 2.6
(1..10).select(&:odd?).map { |x| x*x }
Array#intersection
與在數組上調用&等效,但是允許多個參數。
[1,2,3,4,5].intersection([2,3,4], [2,4,5]) #=> [2, 4]
Enumerator::Lazy#eager
會將惰性枚舉數轉換爲非惰性枚舉數。
(1..).lazy
.select(&:odd?) # lazy
.take(3) # lazy
.eager # next operation will be non-lazy
.map { |x| x * x } #=> [1, 9, 25]
參數轉發語法
添加了新語法( ...
)以允許 轉發方法的所有參數。
def add(a, b)
a + b
end
def add_and_double(...)
add(...) * 2
end
add_and_double(2, 3) #=> 10
Args關鍵字棄用
在先前的Ruby版本中, 如果您有一個帶有關鍵字參數的方法, 並以哈希作爲最後一個參數來調用它, 哈希將被轉換爲關鍵字args。 但是,此方法已被棄用 以期在3.0中刪除此行爲。 現在,這將引起警告。
def foo(key: 1)
key
end
foo({ key: 2 })
#=> 43
# warning: The last argument is used as the keyword parameter
# warning: for `foo' defined here
splat運算符可用於將哈希轉換爲關鍵字args。
foo(**{ key: 2 })
Self調用 private方法
private
的行爲已略有變化。 以前,如果您在self
上調用了私有方法, (例如 self.foo
), 將提示 NoMethodError
錯誤。 現在通過self
調用私有方法不再引發錯誤。
除了添加的所有新函數之外, 這個版本也很有趣 對於某些沒有切入的函數。
引入了管道運算符(pipeline), 如下示例
# with pipeline
foo
|> bar 1, 2
|> display
# normal method chaining
foo
.bar(1, 2)
.display
引入了方法參考運算符(method reference) 然後刪除。 這本來可以寫作 File.method(:read)
作爲 File.:read
。
some_uri
.then(&Net::HTTP.:get)
.then(&JSON.:parse)
之所以被恢復,是因爲 Matz和核心團隊 想重新考慮更廣泛的設計 關於函數式編程的函數 可以在Ruby中使用。
鏈接
鏈接:https://www.learnfk.com/article-ruby-2-7-features
來源:Learnfk無涯私塾網