Arnold
Arnold

Reputation: 2420

RoR character class regex

I have the following line of code in my Ruby on Rails app, which checks whether the given string contains Korean characters or not:

isKorean = !/\p{Hangul}/.match(word).nil?

It works perfectly in the console, but raises a syntax error for the actual app:

invalid character property name {Hangul}: /\p{Hangul}/

What am I missing and how can I get it to work?

Upvotes: 8

Views: 902

Answers (1)

Andrew Marshall
Andrew Marshall

Reputation: 96994

This is a character encoding issue, you need to add:

# encoding: utf-8

to the top of the Ruby file you're using that regex in. You can probably use any encoding that the character class you're using exists in instead of UTF-8 if you wish. Note that in Ruby 2.0, UTF-8 is now the default, so this is not needed in Ruby 2.0+.

This is known as a "magic comment". You can and should read more about encoding in Ruby 1.9. Note that encoding in Rails views is handled automatically by config.encoding (set to UTF-8 by default in config/application.rb.

It was likely working in the console because your terminal is set to use UTF-8 already.

Upvotes: 13

Related Questions