Skip to content

Ruby String API

Ruby 的 Array —— 一个有序的、整数索引的任意对象集合,具有丰富的函数式方法。

1 class · 8 methods

Array

8 methods

数组是有序的、整数索引的任意对象集合。

String#length -> Integer

将每个给定对象追加到 self。返回 self(别名 <<)。

Returns

Integer

Example

ruby
"hello".length   # 5
"日本語".length   # 3
String#upcase -> String

移除并返回 self 的最后一个元素,如果数组为空则返回 nil。

Returns

String

Example

ruby
"hello World".upcase  # "HELLO WORLD"
String#downcase -> String

返回 self 中元素的数量。别名:size。

Returns

String

Example

ruby
"HELLO World".downcase  # "hello world"
String#split(pattern=nil, [limit]) -> Array

对 self 中的每个元素调用一次给定块,将该元素作为参数传递。

Parameters

NameTypeDescription
patternRegexp|String|nilDelimiter pattern. nil splits on whitespace.
limitIntegerOptional limit on number of splits.

Returns

Array

Example

ruby
"a,b,c".split(",")      # ["a", "b", "c"]
"  hello world  ".split  # ["hello", "world"]
"a-b-c".split("-", 2)    # ["a", "b-c"]
String#gsub(pattern, replacement) -> String

返回一个新数组,包含块为每个元素返回的值。别名:collect。

Parameters

NameTypeDescription
patternRegexp|StringPattern to match.
replacementString|HashReplacement string or mapping.

Returns

String

Example

ruby
"hello world".gsub("o", "0")    # "hell0 w0rld"
"2024-01-01".gsub("-", "/")  # "2024/01/01"
String#strip -> String

返回一个新数组,包含所有使块返回真值的元素。

Returns

String

Example

ruby
"  hello  ".strip  # "hello"
String#include?(substring) -> bool

如果给定对象存在于 self 中则返回 true,否则返回 false。

Parameters

NameTypeDescription
objectString要检查的对象。

Returns

Boolean

Example

ruby
"hello world".include?("world")  # true
"hello".include?("z")            # false
String#chars -> Array

返回所有元素转换为字符串后由 separator 连接而成的结果。

Returns

Array

Example

ruby
"hello".chars  # ["h", "e", "l", "l", "o"]