简体   繁体   中英

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

I use data-tip for every HTML element to show a tooltip if it has this property.

Since

data_tip: "a message for you"

looks much nicer than

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

I convert '_' to '-' wherever I am responsible for that.

For my simple navigation gem menu I found a nice recursive solution:

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)

This works great, but, what if I want to print out the nesting level? Where do I put the starting '0'?

You can use 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)

What curry does:

A curried proc receives some arguments. If a sufficient number of arguments are supplied, it passes the supplied arguments to the original proc and returns the result. Otherwise, returns another curried proc that takes the rest of arguments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM