Home Ruby 优雅的把字符串的中间变成省略号
Post
Cancel

Ruby 优雅的把字符串的中间变成省略号

原理:    

"abc"[0,1] # => "ab"

"abc"[-2..-1]  # => "bc"   

获得某个字符串的后面几位也可以写成: "abc".chars.last(3).join("")

(参考:https://stackoverflow.com/questions/2174767/extracting-the-last-n-characters-from-a-ruby-string )

下面是方法:

  def short_format options
    content = options[:content]
    digit = options[:digit] || 5
    return "#{content[0, digit]}...#{content[(0 - digit).. -1]}"
  end

ruby 简直太优雅了.(通俗的讲,ruby 简直太好用了)

This post is licensed under CC BY 4.0 by the author.