Ruby:@cars.each |car| 之间的区别 对于@cars 中的汽车

发布于 2024-07-29 02:59:20 字数 249 浏览 3 评论 0原文

(抱歉这个新手问题。)在 Ruby 中,循环:

@cars.each do |car| 

for car in @cars do

之间有什么区别?

效率是否存在差异,或者为什么我们需要两种(或更多)方式来表达同一件事? 第二种方式对我来说似乎更优雅/自然,但我可能错过了一些关键的观察,为什么第一种方式可能是更好的选择。

(Sorry for the newbie question.) In Ruby, what is the difference between the loops:

@cars.each do |car| 

and

for car in @cars do

?

is there a difference in efficiency, or why do we need two (or more) ways to express the same thing? The second way seems more elegant/natural to me, but I may be missing some crucial observation, why the first may be the better choice.

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

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

发布评论

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

评论(2

泡沫很甜 2024-08-05 02:59:20

更多人使用 @cars.each 表示法,因为它可以推广到其他方法(例如 #inject#each_with_index#map< /code> 等,以及非迭代器回调)。

for/in 主要只是#each 的语法糖。 两者工作方式的主要区别在于变量作用域:

irb> @cars = %w{ ford chevy honda toyota }
#=> ["ford", "chevy", "honda", "toyota"]
irb> @cars.each { |car| puts car }
ford
chevy
honda
toyota
#=> ["ford", "chevy", "honda", "toyota"]
irb> car
NameError: undefined local variable or method `car` for #<Object:0x399770 @cars=["ford", "chevy", "honda", "toyota"]>
        from (irb):3
        from /usr/local/bin/irb:12:in `<main>`
irb> for car in @cars
     puts car.reverse
     end
drof
yvehc
adnoh
atoyot
#=> ["ford", "chevy", "honda", "toyota"]
irb> car
#=> "toyota"

for/in 随后将迭代器变量保留在作用域中,而 #each 则不然。

就我个人而言,我从不使用 ruby​​ 的 for/in 语法。

More people use the @cars.each notation because that generalizes to other methods (like #inject, #each_with_index, #map, etc, as well as non-iterator callbacks).

for/in is mainly just syntactic sugar for #each. The main difference in how the two work is in variable scoping:

irb> @cars = %w{ ford chevy honda toyota }
#=> ["ford", "chevy", "honda", "toyota"]
irb> @cars.each { |car| puts car }
ford
chevy
honda
toyota
#=> ["ford", "chevy", "honda", "toyota"]
irb> car
NameError: undefined local variable or method `car` for #<Object:0x399770 @cars=["ford", "chevy", "honda", "toyota"]>
        from (irb):3
        from /usr/local/bin/irb:12:in `<main>`
irb> for car in @cars
     puts car.reverse
     end
drof
yvehc
adnoh
atoyot
#=> ["ford", "chevy", "honda", "toyota"]
irb> car
#=> "toyota"

for/in leaves the iterator variable in scope afterwards, while #each doesn't.

Personally, I never use ruby's for/in syntax.

弄潮 2024-08-05 02:59:20

我认为这只是语法糖。 它在功能上是等效的,并且我不知道解释器中存在任何实现差异。

注意 - 您可能会丢失第二个中的“do”。

I think it is just syntactic sugar. It is functionally equivalent, and I am not aware of any implementation difference in the interpreter.

Note - you can lose the 'do' on the second one.

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