Majoris
Majoris

Reputation: 3189

Ruby - rails - split string & print in reverse order

I need to split a string and print it beginning from bottom on my views. The standard way starts reading string from the beginning and prints accordingly. How do I reverse it?

<% @a[:log].to_s.split(/----/).each do |line| %>
<div width='100%'><pre class="log"><%= "#{line}" %></pre></div>
<% end %>


@a[:log] is a string something like this: One ---- Two ---- Three ---- Four

I want this printed reverse starting from Four, instead of One. 

<div width='100%'><pre class="log">Four</pre></div>
<div width='100%'><pre class="log">Three</pre></div>
<div width='100%'><pre class="log">Two</pre></div>
<div width='100%'><pre class="log">One</pre></div>

Upvotes: 0

Views: 842

Answers (3)

steenslag
steenslag

Reputation: 80065

If you don't want an intermediate array (which the reverse method returns), then there is reverse_each.

@a[:log].to_s.split(/----/).reverse_each

Upvotes: 2

mikdiet
mikdiet

Reputation: 10018

@a[:log].to_s.split(/----/).reverse.each

Upvotes: 1

Mischa
Mischa

Reputation: 43298

Instead of:

@a[:log].to_s.split(/----/).each

Do:

@a[:log].to_s.split(/----/).reverse.each

Upvotes: 2

Related Questions