Ruby Output Unicode Character

前端 未结 5 1165
不思量自难忘°
不思量自难忘° 2020-12-24 05:18

I\'m not a Ruby dev by trade, but am using Capistrano for PHP deployments. I\'m trying to cleanup the output of my script and am trying to add a unicode check mark as discus

相关标签:
5条回答
  • 2020-12-24 05:48

    falsetru's answer is incorrect.

    checkmark = "\u2713"
    puts checkmark.encode('utf-8')
    

    This transcodes the checkmark from the current system encoding to UTF-8 encoding. (That works only on a system whose default is already UTF-8.)

    The correct answer is:

    puts checkmark.force_encoding('utf-8')
    

    This modifies the string's encoding, without modifying any character sequence.

    0 讨论(0)
  • 2020-12-24 06:01

    In newer versions of Ruby, you don't need to enforce encoding. Here is an example with 2.1.2:

    2.1.2 :002 > "\u00BD"
     => "½"
    

    Just make sure you use double quotes!

    0 讨论(0)
  • 2020-12-24 06:03

    As an additional note, if you want to print an emoji, you have to surround it with braces.

    irb(main):001:0> "\u{1F600}"
    => "                                                                    
    0 讨论(0)
  • 2020-12-24 06:06

    In Ruby 1.9.x+

    Use String#encode:

    checkmark = "\u2713"
    puts checkmark.encode('utf-8')
    

    prints

    In Ruby 1.8.7

    puts '\u2713'.gsub(/\\u[\da-f]{4}/i) { |m| [m[-4..-1].to_i(16)].pack('U') }
    ✓
    
    0 讨论(0)
  • 2020-12-24 06:07

    Same goes as above in ERB, no forced encoding required, works perfectly, tested at Ruby 2.3.0

        <%= "\u00BD" %>
    

    Much appreciation

    0 讨论(0)
提交回复
热议问题