Skip to content

Instantly share code, notes, and snippets.

@kwappa
Created June 19, 2012 06:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kwappa/2952564 to your computer and use it in GitHub Desktop.
Save kwappa/2952564 to your computer and use it in GitHub Desktop.
マルチバイト文字まじりの文字列を等幅フォントで表示するために文字数を数える
# -*- coding: utf-8 -*-
require 'rspec'
class String
def mb_width
self.split('').inject(0) { |r, c| c =~ /^[ -~。-゚]*$/ ? r += 1 : r += 2 ; r }
end
end
describe String do
context '#mb_width' do
specify "should return 4 if 'hoge' given" do
"hoge".mb_width.should == 4
end
specify "should return 11 if 'ほげandぴよ' given" do
"ほげandぴよ".mb_width.should == 11
end
end
end
@kwappa
Copy link
Author

kwappa commented Jun 19, 2012

http://twitter.com/#!/rosylilly/status/214970048102678528

@kwappa これじゃだめ? "あいうえお".split(//).inject(0){| sum, char | sum += char.bytesize > 1 ? 2 : 1 }

@kwappa
Copy link
Author

kwappa commented Jun 19, 2012

6行目、最後にr返さなくてもいいのか。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment