Skip to content

Instantly share code, notes, and snippets.

@kwappa
Created Jun 19, 2012
Embed
What would you like to do?
マルチバイト文字まじりの文字列を等幅フォントで表示するために文字数を数える
# -*- 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

This comment has been minimized.

Copy link
Owner Author

@kwappa kwappa commented Jun 19, 2012

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

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

@kwappa

This comment has been minimized.

Copy link
Owner Author

@kwappa 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