2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Crystalでは delete_prefix, delete_suffix は lchop と rchop

Posted at

タイトルの通りです。

Rubyには、delete_prefix delete_suffix という便利なメソッドがあります。これは Ruby 2.5 の時点で@sonotsさんによって追加されたメソッドで、正規表現が苦手な自分は愛用していました。

Ruby 2.5 の String クラスに文字列から接頭辞や接尾辞を削除する delete_prefix と delete_suffix メソッドを追加しました。

'foobar'.delete_prefix('foo') #=> 'bar'
'foobar'.delete_suffix('bar') #=> 'foo'

いままでは、接頭辞の削除をするのに

'foobar'.sub(/^foo/, '') #=> 'bar'

のようにしている人が多かったと思いますが、このコードは正規表現を使うことになるので遅いです。高速に削除するには

'foobar'[3..-1] if 'foobar'.start_with?('foo')

のようにする必要があったのですが、これは面倒ですね。これを >String#delete_prefix を呼ぶだけで行うことができるようになりました。

これらのメソッドが Crystal では見当たらなかったのですが、別名で存在することがわかりました。それが、lchoprchop です。

"hello".lchop('h')   # => "ello"
"hello".lchop('g')   # => "hello"
"hello".lchop("hel") # => "lo"
"hello".lchop("eh")  # => "hello"
"string".rchop('g')   # => "strin"
"string".rchop('x')   # => "string"
"string".rchop("ing") # => "str"
"string".rchop("inx") # => "string"

lchop, rchop は引数がない場合最初/最後の文字が削除されるようです。
lchop?, rchop? は chop されなかった場合はnilを返します。

CrystalとRubyは多くの点で似通っていますが、このように異なる名前がついていることも多いので注意が必要ですね。

この記事は以上です。

2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?