halfbit
halfbit

Reputation: 3939

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'?

Upvotes: 1

Views: 81

Answers (1)

Uri Agassi
Uri Agassi

Reputation: 37409

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.

Upvotes: 4

Related Questions