user6589814 user6589814 - 1 month ago 11
Ruby Question

Ruby on Rails - Add limit, order and sum on File.open

In my application I have a

.txt
file that I
open/read
on users profile view. That
.txt
file contains some numbers.

This is what i have so far:

f = File.open("public/users/14/user.txt", "r")
- f.each_line do |d|
%p= d


I can
put
out all the numbers that is on that file. Is it any way to add
limit
&
order (start from bottom to top)
.

I tried:

f.limit(4).order('DESC').each_line do |d|


and

File.open("public/users/14/user.txt", "r").limit(5)


When I try these I get error:
undefined method limit
or
undefined method order
.

Is it also possible to
sum
all the numbers on that file?

Answer

This should work:

@lines = IO.readlines('public/users/14/user.txt').sort.reverse.first(4)

You should put the above in your controller and use it in your view:

- @lines.each do |line|
  %p= line
Comments