String 的变体定义了转换名称用于不同目的的新方法。例如,你可以从类名推断出表名。
'ScaleScore'.tableize # => "scale_scores"
- A
- B
- C
- D
- E
- F
- H
- I
- L
- M
- P
- R
- S
- T
- U
常量
| BLANK_RE | = | /\A[[:space:]]*\z/ |
| ENCODED_BLANKS | = | Concurrent::Map.new do |h, enc| h[enc] = Regexp.new(BLANK_RE.source.encode(enc), BLANK_RE.options | Regexp::FIXEDENCODING) end |
实例公共方法
acts_like_string?() 链接
为类似 String 的类启用更可预测的鸭子类型。请参阅 Object#acts_like?。
源代码: 显示 | 在 GitHub 上
# File activesupport/lib/active_support/core_ext/string/behavior.rb, line 5 def acts_like_string? true end
at(position) 链接
如果传递单个整数,则在指定位置返回一个字符的子字符串。字符串的第一个字符位于位置 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
源代码: 显示 | 在 GitHub 上
# 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]
源代码: 显示 | 在 GitHub 上
# File activesupport/lib/active_support/core_ext/object/blank.rb, line 153 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
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"
源代码: 显示 | 在 GitHub 上
# 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 为模型到表名所做的那样。请注意,这返回的是字符串而不是类。(要转换为实际类,请在 classify 之后调用 constantize。)
'ham_and_eggs'.classify # => "HamAndEgg" 'posts'.classify # => "Post"
源代码: 显示 | 在 GitHub 上
# File activesupport/lib/active_support/core_ext/string/inflections.rb, line 239 def classify ActiveSupport::Inflector.classify(self) end
constantize() 链接
constantize 尝试查找字符串中指定的已声明常量。当名称不是 CamelCase 或未初始化时,它会引发 NameError。
'Module'.constantize # => Module 'Class'.constantize # => Class 'blargle'.constantize # => NameError: wrong constant name blargle
源代码: 显示 | 在 GitHub 上
# File activesupport/lib/active_support/core_ext/string/inflections.rb, line 73 def constantize ActiveSupport::Inflector.constantize(self) end
dasherize() 链接
源代码: 显示 | 在 GitHub 上
# 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。
源代码: 显示 | 在 GitHub 上
# 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。
源代码: 显示 | 在 GitHub 上
# 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 # => ""
源代码: 显示 | 在 GitHub 上
# 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
源代码: 显示 | 在 GitHub 上
# 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"
源代码: 显示 | 在 GitHub 上
# 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"
源代码: 显示 | 在 GitHub 上
# 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(position) 链接
从给定位置返回到字符串末尾的子字符串。如果位置为负数,则从字符串末尾开始计数。
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"
源代码: 显示 | 在 GitHub 上
# File activesupport/lib/active_support/core_ext/string/access.rb, line 46 def from(position) self[position, length] end
html_safe() 链接
将字符串标记为安全。它将在 HTML 中插入,而不会执行任何额外的转义。确保字符串不包含恶意内容是您的责任。此方法等同于视图中的 raw 助手。建议使用 sanitize 而不是此方法。切勿将其应用于用户输入。
源代码: 显示 | 在 GitHub 上
# 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"
源代码: 显示 | 在 GitHub 上
# 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.zone 或 Time.zone_default,则将 String 转换为当前时区的 TimeWithZone,否则通过 String#to_time 将 String 转换为 Time。
源代码: 显示 | 在 GitHub 上
# 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 通常是单个空格或制表符,但它可以是任何字符串。
第三个参数 indent_empty_lines 是一个标志,指示是否应缩进空行。默认为 false。
"foo\n\nbar".indent(2) # => " foo\n\n bar" "foo\n\nbar".indent(2, nil, true) # => " foo\n \n bar"
源代码: 显示 | 在 GitHub 上
# 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。
源代码: 显示 | 在 GitHub 上
# 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
源代码: 显示 | 在 GitHub 上
# 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
源代码: 显示 | 在 GitHub 上
# File activesupport/lib/active_support/core_ext/string/multibyte.rb, line 57 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"
源代码: 显示 | 在 GitHub 上
# 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 方法版本在该代理类上定义。如果代理类不响应某个方法,则将其转发给封装的字符串。
>> "lj".mb_chars.upcase.to_s # => "LJ"
注意:Ruby 2.4 及更高版本支持本机 Unicode 大小写映射。
>> "lj".upcase # => "LJ"
方法链¶ ↑
Chars 代理上的所有通常返回字符串的方法都将返回 Chars 对象。这允许对这些方法的结果进行方法链式调用。
name.mb_chars.reverse.length # => 12
互操作性和配置¶ ↑
Chars 对象尽可能地与 String 对象互换:String 和 Char 之间的排序和比较按预期工作。“bang!” 方法会更改 Chars 对象中的内部字符串表示。通过调用 to_s 可以轻松解决互操作性问题。
有关 Chars 代理上定义的方法的更多信息,请参阅 ActiveSupport::Multibyte::Chars。有关如何更改默认多字节行为的信息,请参阅 ActiveSupport::Multibyte。
源代码: 显示 | 在 GitHub 上
# File activesupport/lib/active_support/core_ext/string/multibyte.rb, line 37 def mb_chars ActiveSupport.deprecator.warn( "String#mb_chars is deprecated and will be removed in Rails 8.2. " \ "Use normal string methods instead." ) if ActiveSupport::Multibyte.proxy_class == ActiveSupport::Multibyte::Chars ActiveSupport::Multibyte::Chars.new(self, deprecation: false) else ActiveSupport::Multibyte.proxy_class.new(self) end 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>
源代码: 显示 | 在 GitHub 上
# 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"
源代码: 显示 | 在 GitHub 上
# 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"
源代码: 显示 | 在 GitHub 上
# 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 "
源代码: 显示 | 在 GitHub 上
# 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
源代码: 显示 | 在 GitHub 上
# 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"
源代码: 显示 | 在 GitHub 上
# 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"
源代码: 显示 | 在 GitHub 上
# File activesupport/lib/active_support/core_ext/string/filters.rb, line 13 def squish dup.squish! end
squish!() 链接
执行就地 squish 操作。请参阅 String#squish。
str = " foo bar \n \t boo" str.squish! # => "foo bar boo" str # => "foo bar boo"
源代码: 显示 | 在 GitHub 上
# File activesupport/lib/active_support/core_ext/string/filters.rb, line 21 def squish! gsub!(/[[:space:]]+/, " ") strip! self end
strip_heredoc() 链接
剥离 heredoc 中的缩进。
例如,在
if options[:usage] puts <<-USAGE.strip_heredoc This command does such and such. Supported options are: -h This message ... USAGE end
用户将看到使用消息与左边距对齐。
严格来说,它会查找整个字符串中缩进最少的非空行,并移除该数量的前导空格。
源代码: 显示 | 在 GitHub 上
# 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"
源代码: 显示 | 在 GitHub 上
# File activesupport/lib/active_support/core_ext/string/inflections.rb, line 227 def tableize ActiveSupport::Inflector.tableize(self) end
titleize(keep_id_suffix: false) 链接
将所有单词的首字母大写,并替换字符串中的某些字符以创建更美观的标题。titleize 旨在生成漂亮的输出。它不用于 Rails 内部。
可以通过将可选参数 keep_id_suffix 设置为 true 来保留末尾的 “_id”、“Id” 等并将其大写。默认情况下,此参数为 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"
源代码: 显示 | 在 GitHub 上
# 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"
源代码: 显示 | 在 GitHub 上
# 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
源代码: 显示 | 在 GitHub 上
# 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
源代码: 显示 | 在 GitHub 上
# 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
源代码: 显示 | 在 GitHub 上
# 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.intersect?(used_keys) 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 字符串(默认为“…”)替换。总长度不会超过 truncate_to,除非 text 和 :omission 都大于 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)"
源代码: 显示 | 在 GitHub 上
# 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。
源代码: 显示 | 在 GitHub 上
# 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.force_encoding(encoding).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)"
源代码: 显示 | 在 GitHub 上
# 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"
源代码: 显示 | 在 GitHub 上
# 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 # => ""
源代码: 显示 | 在 GitHub 上
# File activesupport/lib/active_support/core_ext/string/inflections.rb, line 273 def upcase_first ActiveSupport::Inflector.upcase_first(self) end