0

Sorry, I am just learning how to use Rails.

I've got a simple .txt file asset which I would like to pull random Strings from to display on my landing page.

Is there an easy way in Rails to do this?

MZaragoza
  • 10,108
  • 9
  • 71
  • 116
z3po
  • 119
  • 1
  • 6

2 Answers2

2

Assuming each string is in a separate line, you can do this:

strings = File.readlines('path/to/file.txt')

Then, to get a random string use sample, like this:

strings.sample

If you wan't more than one random string, just use sample with an argument, for example:

strings.sample(3)

This will return an array with 3 random lines from strings array.

Finally, you can do all in one line, for example, try this in the controller:

@string = File.readlines('path/to/file.txt').sample

And you will have @string available to use in the view.

Gerry
  • 10,337
  • 3
  • 31
  • 40
1

So you are not giving me much. but I am going to assume that you want to get 1 line of a text file.

This is how I would do it

File.readlines("my/file/path.txt").sample

I hope that get you started :)

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
MZaragoza
  • 10,108
  • 9
  • 71
  • 116