跳到內容 跳到搜尋

字串 變化定義 字串 類別上的新方法,以轉換名稱供不同目的使用。例如,您可以從類別名稱找出資料表的名稱。

'ScaleScore'.tableize # => "scale_scores"
方法
A
B
C
D
E
F
H
I
L
M
P
R
S
T
U

常數

空白_RE = /\A[[:space:]]*\z/
 
編碼_空白 = Concurrent::Map.new do |h, enc| h[enc] = Regexp.new(BLANK_RE.source.encode(enc), BLANK_RE.options | Regexp::FIXEDENCODING) end
 

執行個體公開方法

acts_like_string?()

在類似字串的類別上啟用更可預測的鴨子型別。請參閱 Object#acts_like?

# File activesupport/lib/active_support/core_ext/string/behavior.rb, line 5
def acts_like_string?
  true
end

at(位置)

如果您傳遞一個整數,則會傳回該位置的一個字元子字串。字串的第一個字元位於位置 0,下一個位於位置 1,依此類推。如果提供範圍,則會傳回包含範圍給定偏移量處字元的子字串。在兩種情況下,如果偏移量為負數,則會從字串的結尾開始計算。如果初始偏移量超出字串,則會傳回 nil。如果範圍的開頭大於字串的結尾,則會傳回空字串。

str = "hello"
str.at(0)      # => "h"
str.at(1..3)   # => "ell"
str.at(-2)     # => "l"
str.at(-2..-1) # => "lo"
str.at(5)      # => nil
str.at(5..-1)  # => ""

如果給定 Regexp,則會傳回字串的匹配部分。如果給定 String,則如果該字串出現在字串中,則會傳回該字串。在兩種情況下,如果沒有匹配,則會傳回 nil

str = "hello"
str.at(/lo/) # => "lo"
str.at(/ol/) # => nil
str.at("lo") # => "lo"
str.at("ol") # => nil
# File activesupport/lib/active_support/core_ext/string/access.rb, line 29
def at(position)
  self[position]
end

blank?()

如果字串為空或只包含空白,則為空白

''.blank?       # => true
'   '.blank?    # => true
"\t\n\r".blank? # => true
' blah '.blank? # => false

支援 Unicode 空白

"\u00a0".blank? # => true

@return [true, false]

# File activesupport/lib/active_support/core_ext/object/blank.rb, line 121
def blank?
  # The regexp that matches blank strings is expensive. For the case of empty
  # strings we can speed up this method (~3.5x) with an empty? call. The
  # penalty for the rest of strings is marginal.
  empty? ||
    begin
      BLANK_RE.match?(self)
    rescue Encoding::CompatibilityError
      ENCODED_BLANKS[self.encoding].match?(self)
    end
end

camelcase(first_letter = :upper)

別名:camelize

camelize(first_letter = :upper)

預設情況下,camelize 會將字串轉換為 UpperCamelCase。如果 camelize 的引數設定為 :lower,則 camelize 會產生 lowerCamelCase。

camelize 也會將「/」轉換為「::」,這有助於將路徑轉換為命名空間。

'active_record'.camelize                # => "ActiveRecord"
'active_record'.camelize(:lower)        # => "activeRecord"
'active_record/errors'.camelize         # => "ActiveRecord::Errors"
'active_record/errors'.camelize(:lower) # => "activeRecord::Errors"

請參閱 ActiveSupport::Inflector.camelize

別名為:camelcase
# File activesupport/lib/active_support/core_ext/string/inflections.rb, line 101
def camelize(first_letter = :upper)
  case first_letter
  when :upper
    ActiveSupport::Inflector.camelize(self, true)
  when :lower
    ActiveSupport::Inflector.camelize(self, false)
  else
    raise ArgumentError, "Invalid option, use either :upper or :lower."
  end
end

classify()

從複數表格名稱建立類別名稱,就像 Rails 對表格名稱建立模型一樣。請注意,這會傳回字串,而不是類別。(若要轉換為實際類別,請將 classifyconstantize 一起使用。)

'ham_and_eggs'.classify # => "HamAndEgg"
'posts'.classify        # => "Post"

請參閱 ActiveSupport::Inflector.classify

# File activesupport/lib/active_support/core_ext/string/inflections.rb, line 239
def classify
  ActiveSupport::Inflector.classify(self)
end

constantize()

constantize 會嘗試尋找字串中指定名稱的已宣告常數。如果名稱不是駝峰式大小寫或未初始化,它會引發 NameError

'Module'.constantize  # => Module
'Class'.constantize   # => Class
'blargle'.constantize # => NameError: wrong constant name blargle

請參閱 ActiveSupport::Inflector.constantize

# File activesupport/lib/active_support/core_ext/string/inflections.rb, line 73
def constantize
  ActiveSupport::Inflector.constantize(self)
end

dasherize()

將字串中的底線替換為破折號。

'puni_puni'.dasherize # => "puni-puni"

請參閱 ActiveSupport::Inflector.dasherize

# File activesupport/lib/active_support/core_ext/string/inflections.rb, line 148
def dasherize
  ActiveSupport::Inflector.dasherize(self)
end

deconstantize()

從字串中的常數表達式中移除最右邊的區段。

'Net::HTTP'.deconstantize   # => "Net"
'::Net::HTTP'.deconstantize # => "::Net"
'String'.deconstantize      # => ""
'::String'.deconstantize    # => ""
''.deconstantize            # => ""

請參閱 ActiveSupport::Inflector.deconstantize

另請參閱 demodulize

# File activesupport/lib/active_support/core_ext/string/inflections.rb, line 177
def deconstantize
  ActiveSupport::Inflector.deconstantize(self)
end

demodulize()

移除字串中常數表達式的模組部分。

'ActiveSupport::Inflector::Inflections'.demodulize # => "Inflections"
'Inflections'.demodulize                           # => "Inflections"
'::Inflections'.demodulize                         # => "Inflections"
''.demodulize                                      # => ''

請參閱 ActiveSupport::Inflector.demodulize

另請參閱 deconstantize

# File activesupport/lib/active_support/core_ext/string/inflections.rb, line 162
def demodulize
  ActiveSupport::Inflector.demodulize(self)
end

downcase_first()

將第一個字元轉換為小寫。

'If they enjoyed The Matrix'.downcase_first # => "if they enjoyed The Matrix"
'I'.downcase_first                          # => "i"
''.downcase_first                           # => ""

請參閱 ActiveSupport::Inflector.downcase_first

# File activesupport/lib/active_support/core_ext/string/inflections.rb, line 284
def downcase_first
  ActiveSupport::Inflector.downcase_first(self)
end

exclude?(string)

String#include? 的反向。如果字串不包含其他字串,則傳回 true。

"hello".exclude? "lo" # => false
"hello".exclude? "ol" # => true
"hello".exclude? ?h   # => false
# File activesupport/lib/active_support/core_ext/string/exclude.rb, line 10
def exclude?(string)
  !include?(string)
end

first(limit = 1)

傳回第一個字元。如果提供限制,則傳回從字串開頭到達到限制值為止的子字串。如果給定的限制大於或等於字串長度,則傳回 self 的副本。

str = "hello"
str.first    # => "h"
str.first(1) # => "h"
str.first(2) # => "he"
str.first(0) # => ""
str.first(6) # => "hello"
# File activesupport/lib/active_support/core_ext/string/access.rb, line 78
def first(limit = 1)
  self[0, limit] || raise(ArgumentError, "negative limit")
end

foreign_key(separate_class_name_and_id_with_underscore = true)

從類別名稱建立外來鍵名稱。separate_class_name_and_id_with_underscore 設定方法是否要在名稱和「id」之間加上「_」。

'Message'.foreign_key        # => "message_id"
'Message'.foreign_key(false) # => "messageid"
'Admin::Post'.foreign_key    # => "post_id"

請參閱 ActiveSupport::Inflector.foreign_key

# File activesupport/lib/active_support/core_ext/string/inflections.rb, line 297
def foreign_key(separate_class_name_and_id_with_underscore = true)
  ActiveSupport::Inflector.foreign_key(self, separate_class_name_and_id_with_underscore)
end

from(位置)

傳回從指定位置到字串尾端的子字串。如果位置為負數,則從字串尾端開始計算。

str = "hello"
str.from(0)  # => "hello"
str.from(3)  # => "lo"
str.from(-2) # => "lo"

您可以將它與 to 方法混合使用,並執行一些有趣的事情,例如

str = "hello"
str.from(0).to(-1) # => "hello"
str.from(1).to(-2) # => "ell"
# File activesupport/lib/active_support/core_ext/string/access.rb, line 46
def from(position)
  self[position, length]
end

html_safe()

將字串標記為可信賴的安全。它將插入 HTML 中,且不執行其他跳脫。您有責任確保字串不包含任何惡意內容。此方法等同於檢視中的 raw 輔助程式。建議您使用 sanitize 取代此方法。切勿在使用者輸入上呼叫它。

# File activesupport/lib/active_support/core_ext/string/output_safety.rb, line 232
def html_safe
  ActiveSupport::SafeBuffer.new(self)
end

humanize(capitalize: true, keep_id_suffix: false)

將第一個字元大寫,將底線改為空格,並(預設)移除尾端的「_id」(如果存在)。與 titleize 相同,這是為了建立漂亮的輸出。

可以透過將選用參數 capitalize 設為 false 來關閉第一個字元的變大寫。預設此參數為 true。

可以透過將選用參數 keep_id_suffix 設為 true 來保留並將尾端的「_id」大寫。預設此參數為 false。

'employee_salary'.humanize                    # => "Employee salary"
'author_id'.humanize                          # => "Author"
'author_id'.humanize(capitalize: false)       # => "author"
'_id'.humanize                                # => "Id"
'author_id'.humanize(keep_id_suffix: true)    # => "Author id"

請參閱 ActiveSupport::Inflector.humanize

# File activesupport/lib/active_support/core_ext/string/inflections.rb, line 262
def humanize(capitalize: true, keep_id_suffix: false)
  ActiveSupport::Inflector.humanize(self, capitalize: capitalize, keep_id_suffix: keep_id_suffix)
end

in_time_zone(zone = ::Time.zone)

如果已設定 Time.zoneTime.zone_default,則將 String 轉換為目前時區中的 TimeWithZone,否則透過 String#to_timeString 轉換為 Time

# File activesupport/lib/active_support/core_ext/string/zones.rb, line 9
def in_time_zone(zone = ::Time.zone)
  if zone
    ::Time.find_zone!(zone).parse(self)
  else
    to_time
  end
end

indent(amount, indent_string = nil, indent_empty_lines = false)

縮排接收者的行

<<EOS.indent(2)
def some_method
  some_code
end
EOS
# =>
  def some_method
    some_code
  end

第二個引數 `indent_string` 指定要使用的縮排字串。預設為 `nil`,此方法會透過窺探第一個縮排行來猜測,如果沒有則改用空白。

"  foo".indent(2)        # => "    foo"
"foo\n\t\tbar".indent(2) # => "\t\tfoo\n\t\t\t\tbar"
"foo".indent(2, "\t")    # => "\t\tfoo"

雖然 `indent_string` 通常是一個空白或一個 tab,但它可以是任何字串。

第三個引數 `indent_empty_lines` 是個旗標,表示是否要縮排空白行。預設為 false。

"foo\n\nbar".indent(2)            # => "  foo\n\n  bar"
"foo\n\nbar".indent(2, nil, true) # => "  foo\n  \n  bar"
# File activesupport/lib/active_support/core_ext/string/indent.rb, line 42
def indent(amount, indent_string = nil, indent_empty_lines = false)
  dup.tap { |_| _.indent!(amount, indent_string, indent_empty_lines) }
end

indent!(amount, indent_string = nil, indent_empty_lines = false)

與 `indent` 相同,除了它會就地縮排接收者。

傳回縮排後的字串,或如果沒有任何要縮排的內容,則傳回 `nil`。

# File activesupport/lib/active_support/core_ext/string/indent.rb, line 7
def indent!(amount, indent_string = nil, indent_empty_lines = false)
  indent_string = indent_string || self[/^[ \t]/] || " "
  re = indent_empty_lines ? /^/ : /^(?!$)/
  gsub!(re, indent_string * amount)
end

inquiry()

使用 ActiveSupport::StringInquirer 類別包裝目前的字串,這會提供更美觀的方式來測試相等性。

env = 'production'.inquiry
env.production?  # => true
env.development? # => false
# File activesupport/lib/active_support/core_ext/string/inquiry.rb, line 13
def inquiry
  ActiveSupport::StringInquirer.new(self)
end

is_utf8?()

如果字串具有 utf_8 編碼,則傳回 `true`。

utf_8_str = "some string".encode "UTF-8"
iso_str = "some string".encode "ISO-8859-1"

utf_8_str.is_utf8? # => true
iso_str.is_utf8?   # => false
# File activesupport/lib/active_support/core_ext/string/multibyte.rb, line 48
def is_utf8?
  case encoding
  when Encoding::UTF_8, Encoding::US_ASCII
    valid_encoding?
  when Encoding::ASCII_8BIT
    dup.force_encoding(Encoding::UTF_8).valid_encoding?
  else
    false
  end
end

last(limit = 1)

傳回字串的最後一個字元。如果提供一個限制,則從字串的結尾傳回一個子字串,直到它達到限制值(從後往前算)。如果給定的限制大於或等於字串長度,則傳回 self 的一個拷貝。

str = "hello"
str.last    # => "o"
str.last(1) # => "o"
str.last(2) # => "lo"
str.last(0) # => ""
str.last(6) # => "hello"
# File activesupport/lib/active_support/core_ext/string/access.rb, line 92
def last(limit = 1)
  self[[length - limit, 0].max, limit] || raise(ArgumentError, "negative limit")
end

mb_chars()

多位元組代理

mb_chars 是字串方法的多位元組安全代理。

它建立並傳回 ActiveSupport::Multibyte::Chars 類別的執行個體,其中封裝了原始字串。所有 String 方法的 Unicode 安全版本都定義在此代理類別中。如果代理類別未回應特定方法,則會將其轉發至封裝的字串。

>> "lj".mb_chars.upcase.to_s
=> "LJ"

注意:Ruby 2.4 及更新版本支援原生 Unicode 大小寫對應

>> "lj".upcase
=> "LJ"

Method 串接

Chars 代理中所有通常會傳回字串的方法都會傳回 Chars 物件。這允許在這些方法的任何結果上進行方法串接。

name.mb_chars.reverse.length # => 12

互通性和組態

Chars 物件會盡可能地與 String 物件互換:String 與 Char 之間的排序和比較會如預期般運作。驚嘆號方法會變更 Chars 物件中的內部字串表示。互通性問題可以用 to_s 呼叫輕鬆解決。

如需瞭解 Chars 代理中定義的方法,請參閱 ActiveSupport::Multibyte::Chars。如需瞭解如何變更預設的多位元組行為,請參閱 ActiveSupport::Multibyte

# File activesupport/lib/active_support/core_ext/string/multibyte.rb, line 37
def mb_chars
  ActiveSupport::Multibyte.proxy_class.new(self)
end

parameterize(separator: "-", preserve_case: false, locale: nil)

取代字串中的特殊字元,以便可以用於「美觀」URL 的一部分。

如果指定了選用參數 locale,則會將字詞參數化為該語言的字詞。預設情況下,此參數設定為 nil,且會使用已組態的 I18n.locale

class Person
  def to_param
    "#{id}-#{name.parameterize}"
  end
end

@person = Person.find(1)
# => #<Person id: 1, name: "Donald E. Knuth">

<%= link_to(@person.name, person_path) %>
# => <a href="/person/1-donald-e-knuth">Donald E. Knuth</a>

如要保留字串中字元的字母大小寫,請使用 preserve_case 參數。

class Person
  def to_param
    "#{id}-#{name.parameterize(preserve_case: true)}"
  end
end

@person = Person.find(1)
# => #<Person id: 1, name: "Donald E. Knuth">

<%= link_to(@person.name, person_path) %>
# => <a href="/person/1-Donald-E-Knuth">Donald E. Knuth</a>

請參閱 ActiveSupport::Inflector.parameterize

# File activesupport/lib/active_support/core_ext/string/inflections.rb, line 215
def parameterize(separator: "-", preserve_case: false, locale: nil)
  ActiveSupport::Inflector.parameterize(self, separator: separator, preserve_case: preserve_case, locale: locale)
end

pluralize(count = nil, locale = :en)

傳回字串中字詞的複數形式。

如果指定了選用參數 count,則如果 count == 1,則會傳回單數形式。對於 count 的任何其他值,則會傳回複數形式。

如果指定了選用參數 locale,則會將字詞複數化為該語言的字詞。預設情況下,此參數設定為 :en。您必須為英語以外的語言定義自己的變形規則。

'post'.pluralize             # => "posts"
'octopus'.pluralize          # => "octopi"
'sheep'.pluralize            # => "sheep"
'words'.pluralize            # => "words"
'the blue mailman'.pluralize # => "the blue mailmen"
'CamelOctopus'.pluralize     # => "CamelOctopi"
'apple'.pluralize(1)         # => "apple"
'apple'.pluralize(2)         # => "apples"
'ley'.pluralize(:es)         # => "leyes"
'ley'.pluralize(1, :es)      # => "ley"

請參閱 ActiveSupport::Inflector.pluralize

# File activesupport/lib/active_support/core_ext/string/inflections.rb, line 35
def pluralize(count = nil, locale = :en)
  locale = count if count.is_a?(Symbol)
  if count == 1
    dup
  else
    ActiveSupport::Inflector.pluralize(self, locale)
  end
end

remove(*patterns)

傳回一個新的字串,其中已移除所有出現的樣式。

str = "foo bar test"
str.remove(" test")                 # => "foo bar"
str.remove(" test", /bar/)          # => "foo "
str                                 # => "foo bar test"
# File activesupport/lib/active_support/core_ext/string/filters.rb, line 32
def remove(*patterns)
  dup.remove!(*patterns)
end

remove!(*patterns)

透過移除所有出現的樣式來變更字串。

str = "foo bar test"
str.remove!(" test", /bar/)         # => "foo "
str                                 # => "foo "
# File activesupport/lib/active_support/core_ext/string/filters.rb, line 40
def remove!(*patterns)
  patterns.each do |pattern|
    gsub! pattern, ""
  end

  self
end

safe_constantize()

safe_constantize 嘗試尋找字串中指定名稱的已宣告常數。如果名稱不是 CamelCase 或未初始化,則會傳回 nil

'Module'.safe_constantize  # => Module
'Class'.safe_constantize   # => Class
'blargle'.safe_constantize # => nil

請參閱 ActiveSupport::Inflector.safe_constantize

# File activesupport/lib/active_support/core_ext/string/inflections.rb, line 86
def safe_constantize
  ActiveSupport::Inflector.safe_constantize(self)
end

singularize(locale = :en)

pluralize 的反向,傳回字串中單數形式的字詞。

如果指定了選用參數 locale,則會將字詞當成該語言的字詞來單數化。預設情況下,此參數設為 :en。您必須為非英語語言定義自己的變形規則。

'posts'.singularize            # => "post"
'octopi'.singularize           # => "octopus"
'sheep'.singularize            # => "sheep"
'word'.singularize             # => "word"
'the blue mailmen'.singularize # => "the blue mailman"
'CamelOctopi'.singularize      # => "CamelOctopus"
'leyes'.singularize(:es)       # => "ley"

請參閱 ActiveSupport::Inflector.singularize

# File activesupport/lib/active_support/core_ext/string/inflections.rb, line 60
def singularize(locale = :en)
  ActiveSupport::Inflector.singularize(self, locale)
end

squish()

傳回字串,首先移除字串兩端的空白,然後將剩餘的連續空白群組變更為每個空白一個。

請注意,它處理 ASCII 和 Unicode 空白。

%{ Multi-line
   string }.squish                   # => "Multi-line string"
" foo   bar    \n   \t   boo".squish # => "foo bar boo"
# File activesupport/lib/active_support/core_ext/string/filters.rb, line 13
def squish
  dup.squish!
end

squish!()

執行破壞性壓縮。請參閱 String#squish

str = " foo   bar    \n   \t   boo"
str.squish!                         # => "foo bar boo"
str                                 # => "foo bar boo"
# File activesupport/lib/active_support/core_ext/string/filters.rb, line 21
def squish!
  gsub!(/[[:space:]]+/, " ")
  strip!
  self
end

strip_heredoc()

移除 heredocs 中的縮排。

例如,在

if options[:usage]
  puts <<-USAGE.strip_heredoc
    This command does such and such.

    Supported options are:
      -h         This message
      ...
  USAGE
end

使用者會看到靠左對齊的用法訊息。

技術上來說,它會尋找整個字串中最不縮排的非空行,並移除該數量的開頭空白。

# File activesupport/lib/active_support/core_ext/string/strip.rb, line 22
def strip_heredoc
  gsub(/^#{scan(/^[ \t]*(?=\S)/).min}/, "").tap do |stripped|
    stripped.freeze if frozen?
  end
end

tableize()

建立一個表格名稱,就像 Rails 對模型到表格名稱所做的那樣。此方法對字串中最後一個字使用 pluralize 方法。

'RawScaledScorer'.tableize # => "raw_scaled_scorers"
'ham_and_egg'.tableize     # => "ham_and_eggs"
'fancyCategory'.tableize   # => "fancy_categories"

請參閱 ActiveSupport::Inflector.tableize

# File activesupport/lib/active_support/core_ext/string/inflections.rb, line 227
def tableize
  ActiveSupport::Inflector.tableize(self)
end

titlecase(keep_id_suffix: false)

別名:titleize

titleize(keep_id_suffix: false)

將所有字首字母大寫,並替換字串中的一些字元,以建立一個看起來更漂亮的標題。titleize 是用於建立漂亮的輸出。它不用於 Rails 內部。

尾隨的「_id」、「Id」等字串可以透過將選用參數 keep_id_suffix 設為 true 來保留並大寫。預設情況下,此參數為 false。

'man from the boondocks'.titleize                       # => "Man From The Boondocks"
'x-men: the last stand'.titleize                        # => "X Men: The Last Stand"
'string_ending_with_id'.titleize(keep_id_suffix: true)  # => "String Ending With Id"

請參閱 ActiveSupport::Inflector.titleize

別名:titlecase
# File activesupport/lib/active_support/core_ext/string/inflections.rb, line 126
def titleize(keep_id_suffix: false)
  ActiveSupport::Inflector.titleize(self, keep_id_suffix: keep_id_suffix)
end

to(position)

傳回從字串開頭到指定位置的子字串。如果位置為負數,則從字串結尾開始計算。

str = "hello"
str.to(0)  # => "h"
str.to(3)  # => "hell"
str.to(-2) # => "hell"

您可以將它與 from 方法混合使用,並執行一些有趣的事情,例如

str = "hello"
str.from(0).to(-1) # => "hello"
str.from(1).to(-2) # => "ell"
# File activesupport/lib/active_support/core_ext/string/access.rb, line 63
def to(position)
  position += size if position < 0
  self[0, position + 1] || +""
end

to_date()

將字串轉換為 Date 值。

"1-1-2012".to_date   # => Sun, 01 Jan 2012
"01/01/2012".to_date # => Sun, 01 Jan 2012
"2012-12-13".to_date # => Thu, 13 Dec 2012
"12/13/2012".to_date # => ArgumentError: invalid date
# File activesupport/lib/active_support/core_ext/string/conversions.rb, line 47
def to_date
  ::Date.parse(self, false) unless blank?
end

to_datetime()

將字串轉換為 DateTime 值。

"1-1-2012".to_datetime            # => Sun, 01 Jan 2012 00:00:00 +0000
"01/01/2012 23:59:59".to_datetime # => Sun, 01 Jan 2012 23:59:59 +0000
"2012-12-13 12:50".to_datetime    # => Thu, 13 Dec 2012 12:50:00 +0000
"12/13/2012".to_datetime          # => ArgumentError: invalid date
# File activesupport/lib/active_support/core_ext/string/conversions.rb, line 57
def to_datetime
  ::DateTime.parse(self, false) unless blank?
end

to_time(form = :local)

將字串轉換為 Time 值。form 可以是 :utc:local(預設為 :local)。

時間使用 Time.parse 方法進行剖析。如果 form:local,則時間為系統時區。如果缺少日期部分,則使用目前日期,如果缺少時間部分,則假設為 00:00:00。

"13-12-2012".to_time               # => 2012-12-13 00:00:00 +0100
"06:12".to_time                    # => 2012-12-13 06:12:00 +0100
"2012-12-13 06:12".to_time         # => 2012-12-13 06:12:00 +0100
"2012-12-13T06:12".to_time         # => 2012-12-13 06:12:00 +0100
"2012-12-13T06:12".to_time(:utc)   # => 2012-12-13 06:12:00 UTC
"12/13/2012".to_time               # => ArgumentError: argument out of range
"1604326192".to_time               # => ArgumentError: argument out of range
# File activesupport/lib/active_support/core_ext/string/conversions.rb, line 22
def to_time(form = :local)
  parts = Date._parse(self, false)
  used_keys = %i(year mon mday hour min sec sec_fraction offset)
  return if (parts.keys & used_keys).empty?

  now = Time.now
  time = Time.new(
    parts.fetch(:year, now.year),
    parts.fetch(:mon, now.month),
    parts.fetch(:mday, now.day),
    parts.fetch(:hour, 0),
    parts.fetch(:min, 0),
    parts.fetch(:sec, 0) + parts.fetch(:sec_fraction, 0),
    parts.fetch(:offset, form == :utc ? 0 : nil)
  )

  form == :utc ? time.utc : time.to_time
end

truncate(truncate_to, options = {})

如果 text 長度大於 truncate_to,則將指定的 text 縮短為長度 truncate_to

'Once upon a time in a world far far away'.truncate(27)
# => "Once upon a time in a wo..."

傳遞字串或正規表示法 :separator 以在自然斷點處縮短 text

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

'Once upon a time in a world far far away'.truncate(27, separator: /\s/)
# => "Once upon a time in a..."

最後的字元將會替換為 :omission 字串(預設為 “…”)。除非 text:omission 都比 truncate_to 長,否則總長度不會超過 truncate_to

'And they found that many people were sleeping better.'.truncate(25, omission: '... (continued)')
# => "And they f... (continued)"

'And they found that many people were sleeping better.'.truncate(4, omission: '... (continued)')
# => "... (continued)"
# File activesupport/lib/active_support/core_ext/string/filters.rb, line 70
def truncate(truncate_to, options = {})
  return dup unless length > truncate_to

  omission = options[:omission] || "..."
  length_with_room_for_omission = truncate_to - omission.length
  stop = \
    if options[:separator]
      rindex(options[:separator], length_with_room_for_omission) || length_with_room_for_omission
    else
      length_with_room_for_omission
    end

  +"#{self[0, stop]}#{omission}"
end

truncate_bytes(truncate_to, omission: "…")

text 縮短至最多 truncate_to 位元組長度,不會中斷字串編碼,方法是將多位元組字元拆分或將字形群集(「感知字元」)在組合字元處縮短。

>> "🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪".size
=> 20
>> "🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪".bytesize
=> 80
>> "🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪🔪".truncate_bytes(20)
=> "🔪🔪🔪🔪…"

縮短的文字以 :omission 字串結尾,預設為「…」,總長度不超過 truncate_to

:omission 的位元組大小超過 truncate_to 時,會引發 ArgumentError

# File activesupport/lib/active_support/core_ext/string/filters.rb, line 101
def truncate_bytes(truncate_to, omission: "…")
  omission ||= ""

  case
  when bytesize <= truncate_to
    dup
  when omission.bytesize > truncate_to
    raise ArgumentError, "Omission #{omission.inspect} is #{omission.bytesize}, larger than the truncation length of #{truncate_to} bytes"
  when omission.bytesize == truncate_to
    omission.dup
  else
    self.class.new.tap do |cut|
      cut_at = truncate_to - omission.bytesize

      each_grapheme_cluster do |grapheme|
        if cut.bytesize + grapheme.bytesize <= cut_at
          cut << grapheme
        else
          break
        end
      end

      cut << omission
    end
  end
end

truncate_words(words_count, options = {})

在給定的字數 (words_count) 後縮短給定的 text

'Once upon a time in a world far far away'.truncate_words(4)
# => "Once upon a time..."

傳遞字串或正規表示法 :separator 以指定不同的字詞分隔符號

'Once<br>upon<br>a<br>time<br>in<br>a<br>world'.truncate_words(5, separator: '<br>')
# => "Once<br>upon<br>a<br>time<br>in..."

最後的字元將被 :omission 字串取代(預設為「…」)

'And they found that many people were sleeping better.'.truncate_words(5, omission: '... (continued)')
# => "And they found that many... (continued)"
# File activesupport/lib/active_support/core_ext/string/filters.rb, line 142
def truncate_words(words_count, options = {})
  sep = options[:separator] || /\s+/
  sep = Regexp.escape(sep.to_s) unless Regexp === sep
  if self =~ /\A((?>.+?#{sep}){#{words_count - 1}}.+?)#{sep}.*/m
    $1 + (options[:omission] || "...")
  else
    dup
  end
end

underscore()

camelize 的反向操作。從字串中的表達式產生底線分隔、小寫的格式。

underscore 也會將「::」變更為「/」以將命名空間轉換為路徑。

'ActiveModel'.underscore         # => "active_model"
'ActiveModel::Errors'.underscore # => "active_model/errors"

請參閱 ActiveSupport::Inflector.underscore

# File activesupport/lib/active_support/core_ext/string/inflections.rb, line 139
def underscore
  ActiveSupport::Inflector.underscore(self)
end

upcase_first()

將第一個字元轉換為大寫。

'what a Lovely Day'.upcase_first # => "What a Lovely Day"
'w'.upcase_first                 # => "W"
''.upcase_first                  # => ""

請參閱 ActiveSupport::Inflector.upcase_first

# File activesupport/lib/active_support/core_ext/string/inflections.rb, line 273
def upcase_first
  ActiveSupport::Inflector.upcase_first(self)
end