Search code examples
ruby-on-railsstringtextassets

Rails Plain Text Asset Extract String


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?


Solution

  • 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.