连续收集/选择/拒绝/每个时的代码折叠

发布于 2024-08-11 09:05:51 字数 456 浏览 11 评论 0原文

我在 ruby​​ 中经常使用数组和哈希,最终得到一些如下所示的代码:(

sum = two_dimensional_array.select{|i|
  i.collect{|j|
    j.to_i
  }.sum > 5
}.collect{|i|
  i.collect{|j|
    j ** 2
  }.average
}.sum

让我们假设上面的代码示例现在有意义......)

问题是,即使 TextMate(我的编辑器) choice)很容易地选择简单的 {...}do...end 块,它无法弄清楚(这是可以理解的,因为即使我也不能找到折叠上面的“正确”方法)上面的块开始和结束折叠它们的位置。

您将如何折叠上面的代码示例?

PS:考虑到它可以有2层折叠,我只关心外面的连续折叠(带有i的块)

I play around with arrays and hashes quite a lot in ruby and end up with some code that looks like this:

sum = two_dimensional_array.select{|i|
  i.collect{|j|
    j.to_i
  }.sum > 5
}.collect{|i|
  i.collect{|j|
    j ** 2
  }.average
}.sum

(Let's all pretend that the above code sample makes sense now...)

The problem is that even though TextMate (my editor of choice) picks up simple {...} or do...end blocks quite easily, it can't figure out (which is understandable since even I can't find a "correct" way to fold the above) where the above blocks start and end to fold them.

How would you fold the above code sample?

PS: considering that it could have 2 levels of folding, I only care about the outer consecutive ones (the blocks with the i)

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

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

发布评论

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

评论(1

贱贱哒 2024-08-18 09:05:51

老实说,一些令人费解的事情可能会让 TextMate 感到困惑,就像其他必须维护它的人一样,这也包括将来的您。

每当您看到某些内容汇总为单个值时,这就是使用 Enumerable#inject 的好例子。

sum = two_dimensional_array.inject(0) do |sum, row|
  # Convert row to Fixnum equivalent
  row_i = row.collect { |i| i.to_i }

  if (row_i.sum > 5)
    sum += row_i.collect { |i| i ** 2 }.average
  end

  sum # Carry through to next inject call
end

在你的例子中奇怪的是你使用 select 返回完整的数组,据称使用 to_i 转换,但实际上 Enumerable#select 没有做这样的事情,而是拒绝函数返回 nil 的任何数组。我猜这不符合你的价值观。

另外,根据 .average 方法的实现方式,您可能希望使用 0.0 而不是 0 为注入调用提供种子以使用浮点值。

To be honest, something that convoluted is probably confusing TextMate as much as anyone else who has to maintain it, and that includes you in the future.

Whenever you see something that rolls up into a single value, it's a good case for using Enumerable#inject.

sum = two_dimensional_array.inject(0) do |sum, row|
  # Convert row to Fixnum equivalent
  row_i = row.collect { |i| i.to_i }

  if (row_i.sum > 5)
    sum += row_i.collect { |i| i ** 2 }.average
  end

  sum # Carry through to next inject call
end

What's odd in your example is you're using select to return the full array, allegedly converted using to_i, but in fact Enumerable#select does no such thing, and instead rejects any for which the function returns nil. I'm presuming that's none of your values.

Also depending on how your .average method is implemented, you may want to seed the inject call with 0.0 instead of 0 to use a floating-point value.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文