3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

文字列を全角で左詰めする

Last updated at Posted at 2014-06-26

文字列を任意の長さで左詰めすることができるljustという組み込みのメソッドがあります。
http://docs.ruby-lang.org/ja/2.0.0/method/String/i/ljust.html

以下のように使えば、表示を揃えたりするので便利です。

[["Miyamoto", "Musashi"], ["Sasaki", "Kojiro"]].each do |name|
  puts name[0].ljust(10) + name[1]
end
Miyamoto  Musashi   
Sasaki    Kojiro

しかしながら、全角が混ざったりするとうまく揃わなくなってしまいます。

[["宮本", "武蔵"], ["Sasaki", "Kojiro"]].each do |name|
  puts name[0].ljust(10) + name[1]
end
宮本        武蔵
Sasaki    Kojiro

このようなときは、Mojiというライブラリを使い、全角で揃えてしまえば良さそうです。以下のようにStringクラスへメソッドを追加すれば、同じような感覚で使えるでしょう。

# $ gem install moji
require 'moji'

class String
  raise "String#ljust_to_byte method has already been defined." if method_defined?(:ljust_two_byte)
  def ljust_two_byte(width, padding = ' ')
    Moji.han_to_zen(self.ljust(width, padding).encode('utf-8'))
  end
end

[["宮本", "武蔵"], ["Sasaki", "Kojiro"]].each do |name|
  puts name[0].ljust_two_byte(10) + name[1].ljust_two_byte(10)
end
宮本        武蔵        
Sasaki    Kojiro

Railsで使うなら、lib/ext/string.rb あたりに定義して、
config/application.rb内で

config/application.rb
require 'ext/string'

すれば便利に使えそうです。

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?