8
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.

Rubyで文字列に絵文字が含まれるか判定

Last updated at Posted at 2018-06-04

Rubyで文字列に絵文字が含まれているかを判定し、真偽値を返すメソッドを作ったのですが、見てくれが悪すぎるので誰か他に良い書き方思い浮ぶ方リファクタリングして頂きたい...

メソッド

def emoji_contained?(text)
  # nilは絵文字が含まれていないことにしたい
  return false if text.nil?
  # 絵文字が一文字でも含まれていればその時点でtrueを返す。
  text.each_char do |b|
    return true if b.bytesize == 4
  end
  return false
end

追記

この記事を投稿した一時間後に @techno-tanoC さんに、改良したコードをコメントに載せて頂いたのでそちらも掲載します!ruby2.3以降で絵文字判定される方はこちらのコードを是非採用ください :bow:

def emoji_contained?(text)
  text&.each_char&.any? {|c| c.bytesize == 4 } || false
end
8
2
5

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
8
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?