Ruby on Rails中"for"和“每个"迭代器之间的区别 [英] Difference between 'for' and 'each' Iterators on Ruby on Rails

查看:44
本文介绍了Ruby on Rails中"for"和“每个"迭代器之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Ruby on rails上不同的beetwen'for'和'each'迭代器有一些疑问.

我有这种情况,最佳做法是什么?

application_helper.rb文件中存在的默认方法:

  def milestone_icons
    icons = ["", "icon-world", "icon-star-twohdd-o", "icon-users", "icon-notification", "icon-clock", "icon-eye", "icon-like-filled", "icon-credit-card", "icon-bell" ]
end

选择haml文件中存在的内容

%select.js-select-icons{style: 'width: 50px', name: 'milestone[icon]'}
  - for icon in milestone_icons do
      %option{value: icon, type: "icon", selected: (@generic.icon == icon)}
        = "<i class='#{icon}'></i>".html_safe

解决方案

令人惊讶的是,几乎没有使用Ruby中的for构造.人们倾向于使用each样式的迭代器或其喜欢的朋友之一,例如each_with_indexeach_with_object,因为它们的用途更加广泛,并且通常性能更好.

强烈建议您使用each方法,除非您有非常有说服力的理由.

差异在某种程度上是学术上的,但是使用each的最大优点是您实际上正在与迭代器进行交互,并且您有很多使用该迭代器的方法.实际上,您可以将迭代器从一种方法传递到另一种方法,并且可以将它们链接在一起以建立正确的结构,然后再执行任何工作.

这里的真正肉食是可枚举,其中each是这种迭代器的最基本版本.对于要解决的任何问题,通常有很多更好的选择.

是的,foreach基本相同,但是each更好,因为它有朋友.

I have some doubts about the diference beetwen 'for' and 'each' Iterators on Ruby on rails.

I have this case, how is the best practice for this?

Def(method) present in the application_helper.rb file:

  def milestone_icons
    icons = ["", "icon-world", "icon-star-twohdd-o", "icon-users", "icon-notification", "icon-clock", "icon-eye", "icon-like-filled", "icon-credit-card", "icon-bell" ]
end

Select present in the haml file:

%select.js-select-icons{style: 'width: 50px', name: 'milestone[icon]'}
  - for icon in milestone_icons do
      %option{value: icon, type: "icon", selected: (@generic.icon == icon)}
        = "<i class='#{icon}'></i>".html_safe

解决方案

Surprisingly the for construct in Ruby is hardly ever used. People tend to prefer the each style iterator or one of its friends like each_with_index or each_with_object as those are significantly more versatile and often perform better.

I'd strongly recommend you use the each method unless you have a very compelling reason.

The differences are somewhat academic, but the big advantage of using each is you're actually interacting with an iterator and you have a lot of ways of using that. You can actually pass through an iterator from one method to another, and you can chain them together to set up the right structure before doing any work.

The real meat here is inside Enumerable where each is the most basic version of this kind of iterator. There are many that are often a much better fit for whatever problem you're trying to solve.

So, yes, for and each are basically the same, but each is better because it's got friends.

这篇关于Ruby on Rails中"for"和“每个"迭代器之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆