11

I want to convert a country code like "US" to an Emoji flag, ie transform "US" string to the appropriate Unicode in Ruby.

Here's an equivalent example for Java

mahemoff
  • 44,526
  • 36
  • 160
  • 222

2 Answers2

21

Use tr to translate alphabetic characters to their regional indicator symbols:

'US'.tr('A-Z', "\u{1F1E6}-\u{1F1FF}")
#=> ""

Of course, you can also use the Unicode characters directly:

'US'.tr('A-Z', '-')
#=> ""
Stefan
  • 109,145
  • 14
  • 143
  • 218
6

Here is a port of that to Ruby:

country = 'US'
flagOffset = 0x1F1E6
asciiOffset = 0x41
firstChar = country[0].ord - asciiOffset + flagOffset
secondChar = country[1].ord - asciiOffset + flagOffset
flag = [firstChar, secondChar].pack("U*")
vcsjones
  • 138,677
  • 31
  • 291
  • 286