Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get emoji flag from country code in Ruby

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

like image 669
mahemoff Avatar asked Jun 14 '18 13:06

mahemoff


People also ask

Which country flag is this 🇳 🇱?

🇳🇱 Flag: Netherlands.

How do you get the flag emoji in HTML?

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 .

What is this 🏴 country?

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 (🏴󠁧󠁢󠁷󠁬󠁳󠁿).

What is the country 🇦 🇪?

🇦🇪 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.


2 Answers

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', '🇦-🇿')
#=> "🇺🇸"
like image 145
Stefan Avatar answered Sep 22 '22 00:09

Stefan


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*")
like image 44
vcsjones Avatar answered Sep 20 '22 00:09

vcsjones