Jump to content

The ultimate community for Ruby on Rails developers.


Photo

One-line loop in a view


  • Please log in to reply
2 replies to this topic

#1 starfry

starfry

    Signalman

  • Members
  • 12 posts

Posted 14 May 2014 - 04:10 PM

Hi everyone,

 

I just noticed this. In a view

<% 8.times do |i| %>                                                                
  <%= i %>
<% end %>

prints the numbers 0 thru 7, as one would expect. However, doing it as a one-liner

<%= 8.times { |i| i } %>

only prints one number, 8.

 

 

So something is happening that I don't understand, but would like to. Why does the single line variant not do as one might expect ?

 



#2 arnig1981

arnig1981

    Passenger

  • Members
  • 1 posts

Posted 14 May 2014 - 07:49 PM   Best Answer

It actually does what you would expect. It prints (=) the outcome of '8.times { |i| i } which is '8'. If you open the rails console and type in '8.times { |i| i }' you'll see it.

You could use haml/slim and make it a 2-liner with

 

- 8.times do |i|

  = i


  • Jamie likes this

#3 Ohm

Ohm

    Driver

  • Moderators
  • 490 posts
  • LocationCopenhagen

Posted 15 May 2014 - 11:12 AM

If what you really wanted was 01234567, you could do it like this

<%= 8.times.to_a.join %>

if you want the space between them supply the #join method with a space.


  • Jamie and arnig1981 like this

Blog: http://ohm.sh | Twitter: @madsohm | Work: Lokalebasen.dk





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users