[英]Is there a default block argument in Ruby?
在主要做 ruby 之后,我才剛剛開始做 Groovy。
它有一個默認的“塊參數”, it
實際上並不是 Groovy 的正式術語,但我是 Groovy 的新手。
(1..10).each {println(it)}
紅寶石呢? 有沒有我可以使用的默認值,所以我不必制作|my_block_arg|
每次?
謝謝!
不,您在 Ruby 中沒有“默認”。
雖然,你可以做
(1..10).each(&method(:puts))
就像Andrey Deinekos 的回答所解釋的那樣,沒有默認值。 您可以使用BasicObject#instance_eval或BasicObject#instance_exec設置self
上下文。 我不建議這樣做,因為它有時會導致一些意想不到的結果。 但是,如果您知道自己在做什么,以下仍然是一個選項:
class Enumerator
def with_ie(&block)
return to_enum(__method__) { each.size } unless block_given?
each { |e| e.instance_eval(&block) }
end
end
(1..10).each.with_ie { puts self }
# 1
# 2
# 3
# 4
# 5
# 6
# 7
# 8
# 9
# 10
#=> 1..10
(1..10).map.with_ie { self * self }
#=> [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
(-5..5).select.with_ie { positive? }
#=> [1, 2, 3, 4, 5]
如果您想調用一個方法,您也可以這樣做(-5..5).select(&:positive?)
,但是當您迭代的對象具有實際屬性時,這可能是值得的。 例如:
people.map.with_ie { "#{id}: #{first_name} - #{last_name}" }
請記住,如果您在范圍內有局部變量id
、 first_name
或last_name
,則將使用它們而不是對象上的方法。 這對於傳遞多個塊參數的散列或Enumerable方法也不太適用。 在這種情況下, self
被設置為一個包含參數的數組。 例如:
{a: 1, b: 2}.map.with_ie { self }
#=> [[:a, 1], [:b, 2]]
{a: 1, b: 2}.map.with_ie { self[0] }
#=> [:a, :b]
從 Ruby 2.7 開始,您可以使用編號塊參數:
(1..10).each { puts _1 }
當然,這還沒有得到很好的記錄。 一些參考仍然使用@1
,但以上是在官方 2.7 版本上測試的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.