7

単語全体を切り取らずに、文字列から N 個の記号のみを取得する簡単な方法があるかどうかを知りたいです。

たとえば、製品と製品の説明情報があります。説明の長さは 70 ~ 500 シンボルですが、次のように最初の 70 シンボルのみを表示したい:

コカ・コーラは、歴史上最も人気があり、最も売れている清涼飲料であり、世界で最も有名なブランドでもあります。

2011 年 5 月 8 日、コカ・コーラは 125 周年を迎えました。1886 年にジョージア州アトランタでジョン S. ペンバートン博士によって作成されたコカコーラは、コカコーラ シロップと炭酸水を混ぜて、ジェイコブス薬局で噴水飲料として最初に提供されました。

したがって、通常の部分文字列メソッドでは次のようになります。

Coca-Cola is the most popular and biggest-selling soft drink in histor

そして、これだけを取得する方法が必要です:

Coca-Cola is the most popular and biggest-selling soft drink in ...
4

6 に答える 6

8

区切りオプションで切り捨てを使用するだけです:

truncate("Once upon a time in a world far far away", length: 17)
# => "Once upon a ti..."
truncate("Once upon a time in a world far far away", length: 17, separator: ' ')
# => "Once upon a..."

詳細については、Rails API ドキュメントの truncate ヘルパーを参照してください。

于 2015-01-27T11:05:39.250 に答える
5

このメソッドは、貪欲に最大 70 文字を取得し、その後、目的を達成するためにスペースまたは文字列の末尾に一致する正規表現を使用します。

def truncate(s, max=70, elided = ' ...')
  s.match( /(.{1,#{max}})(?:\s|\z)/ )[1].tap do |res|
    res << elided unless res.length == s.length
  end    
end

s = "Coca-Cola is the most popular and biggest-selling soft drink in history, as well as the best-known brand in the world."
truncate(s)
=> "Coca-Cola is the most popular and biggest-selling soft drink in ..."
于 2013-05-06T16:58:52.837 に答える
2
s = "Coca-Cola is the most popular and biggest-selling soft drink in history, as well as the best-known brand in the world."
s = s.split(" ").each_with_object("") {|x,ob| break ob unless (ob.length + " ".length + x.length <= 70);ob << (" " + x)}.strip
#=> "Coca-Cola is the most popular and biggest-selling soft drink in"
于 2013-05-06T11:39:00.867 に答える
0

(dbenhurの回答に触発されましたが、最初の最大文字数に空白または文字列の終わりがない場合をより適切に処理します。)

def truncate(s, options = { })
  options.reverse_merge!({
     max: 70,
     elided: ' ...'
  });

  s =~ /\A(.{1,#{options[:max]}})(?:\s|\z)/
  if $1.nil? then s[0, options[:max]] + options[:elided]
  elsif $1.length != s.length then $1 + options[:elided]
  else $1
  end
end
于 2015-11-03T20:02:19.143 に答える