car analogy - Ruby: difference between @cars.each do |car| and for car in @cars do -


(Sorry for the newbie question.) In Ruby, what's the difference between loops?

  @car. Car |  

and

  for car @ in car  

?

Is there a difference in efficiency, or why we need two (or more) ways of expressing the same thing? The other way seems to be more beautiful / natural to me, but I can be reminded of some important observation, why it may be the best option first.

More people use @ cars.each notation because these other Methods (such as #inject , #each_with_index , #map , etc., as well as non-iterator callback).

Syntax is mainly for # ish . The main difference in the use of variables in both of these functions is:

  irb> @ Tax =% w {ford Chevy Honda Toyota} # = & gt; ["Ford", "Chevy", "Honda", "Toyota"] irb & gt; @ Cars.each {| Car | Car car} Ford Chevy Honda Toyota # = & gt; ["Ford", "Chevy", "Honda", "Toyota"] irb & gt; Car name: error: # & lt; Undefined local variable or object for the object `car` = cars = [" Ford "," Chevy "," Honda "," Toyota "]> gt; From (IRB): 3 / usr / local / bin / irb: 12: in `& lt; Main & gt; `irb & gt; Inserts the car in the @ car for the car. Reverse and droop yvehc adnoh atoyot # = & gt; ["Ford", "Chevy", "Honda", "Toyota"] irb & gt; Car # = & gt; For "Toyota",  

leaves the variable running in / in the post, while # ish is not.

Personally, I never use the / in syntax for Ruby.


Comments

Popular posts from this blog

c# - ListView onScroll event -

PHP - get image from byte array -

Linux Terminal Problem with Non-Canonical Terminal I/O app -