12

I want to tell ruby that everything is utf8, except when stated otherwise, so I dont have to place these # encoding: utf-8 comments everywhere.

3 Answers 3

16

You can either:

  1. set your RUBYOPT environment variable to "-E utf-8"
  2. or use https://github.com/m-ryan/magic_encoding
3
  • 1
    #1 is not very portable, and #2 is not very nice, but it is at least automatic :)
    – grosser
    May 8, 2011 at 5:29
  • 1
    #1 crashes my Ruby keyboard on Windows 10 + Ruby 2.2. ie, as soon as I try to write any accent, the keyboard stops working on the ruby console (except for interrupts). Jun 4, 2016 at 21:26
  • @Cyril Duchon-Doris the answer was for Ruby 1.9 since ruby 2 UTF-8 is the default encoding.
    – tommasop
    Jun 5, 2016 at 6:47
14

If you're using environment variables, the general way is to use LC_ALL / LANG

Neither is set : fallback to US-ASCII

$ LC_ALL= LANG= ruby -e 'p Encoding.default_external'
#<Encoding:US-ASCII>

Either is set : that value is used

$ LC_ALL=en_US.UTF-8 LANG= ruby -e 'p Encoding.default_external'
#<Encoding:UTF-8>

$ LC_ALL= LANG=en_US.UTF-8 ruby -e 'p Encoding.default_external'
#<Encoding:UTF-8>

Both are set : LC_ALL takes precedence

$ LC_ALL=C LANG=en_US.UTF-8 ruby -e 'p Encoding.default_external'
#<Encoding:US-ASCII>

$ LC_ALL=en_US.UTF-8 LANG=C ruby -e 'p Encoding.default_external'
#<Encoding:UTF-8>
3
  • This is the correct answer if someone needs to add enconding systemwide. Jan 10, 2014 at 14:26
  • What about if I don't have the LC_ALL environment variable on my system. It says that LC_ALL is undefined when I try to use it.
    – desbest
    Aug 14, 2015 at 10:32
  • The above examples are shell code, not Ruby code. To check the value of LC_ALL in Ruby, use ENV['LC_ALL'] Aug 15, 2015 at 11:34
0

I just upgraded from 1.9 to 2.0, but for some reason the default external encoding was still set to ASCII. I was able to fix it by typing the following in Terminal:

export RUBYOPT='-E utf-8'

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.