#! /usr/bin/env ruby # coding: utf-8 classString defcontains_cjk? !!(self =~ /\p{Han}|\p{Katakana}|\p{Hiragana}|\p{Hangul}/) end end
defcountword(text) count = 0 text.split.inject(1) do |sum, word| if word.contains_cjk? sum += word.length else sum += 1 end count = sum end return count end
s = 'The last Olympics was held in 北京' puts "word count = #{countword(s)}"