Ruby:隐式块迭代器

发布于 2024-12-08 17:48:44 字数 181 浏览 0 评论 0原文

有办法做到这一点吗? 而不是:

links.each do |link|
  link.color "red"
end

使迭代器(在 | | 之间)隐式,如下所示:

links.each do
  color "red"
end

Is there a way to do this?
instead of:

links.each do |link|
  link.color "red"
end

make the iterator (between | |) implicit like so:

links.each do
  color "red"
end

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

转瞬即逝 2024-12-15 17:48:44

我很确定这是不可能的。但是,您可以 instance_eval 每个元素,但如果没有充分的理由,我当然不会推荐它

foo = ["test","test2","foo","bar","foobar"]

foo.each do |f|
  f.instance_eval do
    p reverse
  end
end

I am pretty sure that this is not possible. You can however instance_eval each element, but I certainly wouldn't recommend it without good reason

foo = ["test","test2","foo","bar","foobar"]

foo.each do |f|
  f.instance_eval do
    p reverse
  end
end
救赎№ 2024-12-15 17:48:44

我不确定在这种情况下这是否值得付出努力(并且它增加了不必要的复杂性),但很高兴知道您可以执行以下操作:

proc = Proc.new { |i| i.color 'red' }
links.map(&proc)

I'm not sure this is worth the effort in this instance (and it adds unnecessary complexity) but it's nice to know that you can do something like the following:

proc = Proc.new { |i| i.color 'red' }
links.map(&proc)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文