簡體   English   中英

如何在Ruby中將一個塊和一個初始參數傳遞給每個?

[英]How do I pass a block and an initial argument to each in Ruby?

如果每個HTML元素都具有此屬性,我將使用data-tip來顯示工具提示。

以來

data_tip: "a message for you"

看起來比

:"data-tip" => "an other message for rudi"

我負責的地方都將“ _”轉換為“-”。

對於我的simple navigation gem菜單,我找到了一個不錯的遞歸解決方案:

cleanup=Proc.new do |item|
  cleanup_hash item.html_options #<- this does the '_' -> '-'
  item.sub_navigation.items.each(&cleanup) if item.sub_navigation
end
navigation.primary_navigation.items.each(&cleanup)

這很好用,但是,如果我想打印出嵌套級別怎么辦? 我應該將起始的“ 0”放在哪里?

你可以用curry

cleanup=Proc.new do |depth=0, item|
  cleanup_hash item.html_options #<- this does the '_' -> '-'
  item.sub_navigation.items.each(&cleanup.curry[depth + 1]) if item.sub_navigation
end
navigation.primary_navigation.items.each(&cleanup)

咖喱的作用:

咖喱過程接收一些參數。 如果提供了足夠數量的參數,它將提供的參數傳遞給原始proc並返回結果。 否則,返回另一個使用其余參數的咖喱過程。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM