Search code examples
ruby-on-railsrubyspecial-charactersampersand

Replacing in Ruby on Rails code


I have an excel input file like this.

Artist
A & B
C

Here "Artist" is the column header.

The ruby on rails program has this code:

artist_keys = @params.keys.select{|k| k =~ /^artist/i}
@artists = []
artist_keys.each do |artist_key|
  @artists.push @params[artist_key].to_s.encode('utF-8')
end

I want to store "A %26 B", instead of "A & B" in the "artist_key(s)" or "artist(s)" variable.

I tried channging "A & B" to "A %26 B" in the xlsx input file. But then the program faced an error.

So I think this "replace & with %26" should be done by code-level rather than inputfile-level.

How would I be able to do this?


Solution

  • As has been mentioned doing it at output time would be the "best" solution but if you really want to simply find and replace, gsub is your answer.

    artist_keys.each do |artist_key|
      @artists.push @params[artist_key].to_s.gsub('&','%26').encode('utF-8')
    end
    

    However I would not recommend storing like that if at all possible.