9

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
  • 41,502
  • 34
  • 146
  • 213

2 Answers2

17

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
  • 102,972
  • 12
  • 132
  • 203
5

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
  • 133,702
  • 30
  • 291
  • 279