Picking a random (Chinese) character in ruby

Here’s a simple way to choose a random Chinese character in ruby:


The asterisk expands the range, and “sample(1)” gives you one of the entries.

The unicode block 4E00 to 9FFF contains more than 20000 Chinese characters. If that’s not enough for you, you can find more code blocks here: https://en.wikipedia.org/wiki/CJK_Unified_Ideographs

Shoutout to http://yankist.com/blog/2012/11/28/generate-random-string-in-ruby/ for the many versions on how to create a random string.

I need this random Chinese character for my Factory Girl. She’ll create a new Hanzi everytime I call “let”:

let(:hanzi) { FactoryGirl.create(:hanzi) }

This is my Hanzi factory:

factory :hanzi do
sequence(:character) { |n| [*"\u4E00".."\u9FFF"].sample(1).join("") }
sequence(:components) { |n| [*"\u4E00".."\u9FFF"].sample(3).join("") }

The sequence is required to pick a new sample for every test run.