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
🇳🇱 Flag: Netherlands.
The flag emoji is a combination of the two unicode region characters, located at unicode position 127462 for the letter A. For CH (Switzerland), we want the indexes to be 127464 and 127469 .
While officially called United Kingdom, the emoji commonly goes by Union Jack, UK flag, (flag for) Great Britain, or British flag. Under the 2017 release of Emoji 5.0, different flag emoji were created for England (🏴), Scotland (🏴), and Wales (🏴).
🇦🇪 Flag: United Arab Emirates The flag for United Arab Emirates, which may show as the letters AE on some platforms. The Flag: United Arab Emirates emoji is a flag sequence combining 🇦 Regional Indicator Symbol Letter A and 🇪 Regional Indicator Symbol Letter E. These display as a single emoji on supported platforms.
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', '🇦-🇿')
#=> "🇺🇸"
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*")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With