简体   繁体   English

如何在Ruby中将一个块和一个初始参数传递给每个?

[英]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. 如果每个HTML元素都具有此属性,我将使用data-tip来显示工具提示。

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: 对于我的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)

This works great, but, what if I want to print out the nesting level? 这很好用,但是,如果我想打印出嵌套级别怎么办? Where do I put the starting '0'? 我应该将起始的“ 0”放在哪里?

You can use curry 你可以用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. 如果提供了足够数量的参数,它将提供的参数传递给原始proc并返回结果。 Otherwise, returns another curried proc that takes the rest of arguments. 否则,返回另一个使用其余参数的咖喱过程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何转换Ruby块并将其作为参数应用到另一个块? - How do I transform a Ruby block and apply it as an argument to another block? Ruby:如何创建一个块并将其作为参数传递? - Ruby: How to create a block and pass it as an argument? Ruby:如何将块的结果作为参数传递 - Ruby: How to pass the result of an block as an argument 如何将语句作为参数传递给方法中的块? - How do I pass a statement as an argument to a block within a method? Ruby Double(RR)如何为传递给块参数方法的方法调用块设置期望? - Ruby Double (RR) How do I set up expectations for a block of method calls passed to block argument method? 在Ruby的每个块中,如何对块内数组中的最后一条记录进行处理? - In a Ruby each block, how do I do something to the last record in the array within the block? 如何将&:key作为参数传递给map而不是ruby的块? - How to pass &:key as an argument to map instead of a block with ruby? Ruby闭包:如何将args和block作为单个参数返回以传递给方法 - Ruby Closures: How to return args and block as a single argument to pass to a method 如何在Ruby块中传递对象方法作为参数? - How to pass an object method inside a Ruby block as an argument? 如何在Ruby中将方法作为参数传递? - How can I pass a method as an argument in Ruby?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM