本文簡要介紹ruby語言中 String.slice 的用法。
用法
slice(*args)
返回參數指定的self 的子字符串。
當給定單個整數參數 index 時,返回 self 中偏移量 index 的 1 字符子字符串:
'bar'[2] # => "r"
如果 index 為負數,則從 self 的末尾向後計數:
'foo'[-3] # => "f"
如果 index 超出範圍,則返回 nil:
'foo'[3] # => nil
'foo'[-4] # => nil
當給定兩個整數參數 start 和 length 時,返回在 self 偏移量 start 中找到的給定 length 的子字符串:
'foo'[0, 2] # => "fo"
'foo'[0, 0] # => ""
如果 start 為負數,則從 self 的末尾向後計數:
'foo'[-2, 2] # => "oo"
特殊情況:如果 start 等於 self 的長度,則返回一個新的空字符串:
'foo'[3, 2] # => ""
如果 start 超出範圍,則返回 nil:
'foo'[4, 2] # => nil
'foo'[-4, 2] # => nil
如果 length 很大,則返回 self 的尾隨子字符串:
'foo'[1, 50] # => "oo"
如果 length 為負數,則返回 nil:
'foo'[0, -1] # => nil
當給定單個 Range 參數 range 時,從給定的 range 派生 start 和 length 值,並返回如上所示的值:
-
'foo'[0..1]等價於'foo'[0, 2]。 -
'foo'[0...1]等價於'foo'[0, 1]。
當給定 Regexp 參數 regexp 且 capture 參數為 0 時,返回在 self 中找到的第一個匹配子字符串,如果沒有找到,則返回 nil:
'foo'[/o/] # => "o"
'foo'[/x/] # => nil
s = 'hello there'
s[/[aeiou](.)\1/] # => "ell"
s[/[aeiou](.)\1/, 0] # => "ell"
如果給定參數 capture 而不是 0 ,則它應該是整數捕獲組索引或字符串或符號捕獲組名稱;方法調用僅返回指定的捕獲(參見Regexp Capturing):
s = 'hello there'
s[/[aeiou](.)\1/, 1] # => "l"
s[/(?<vowel>[aeiou])(?<non_vowel>[^aeiou])/, "non_vowel"] # => "l"
s[/(?<vowel>[aeiou])(?<non_vowel>[^aeiou])/, :vowel] # => "e"
如果給出了無效的捕獲組索引,則返回 nil。如果給出了無效的捕獲組名稱,則會引發 IndexError。
當給定單個字符串參數 substring 時,如果找到則返返回自 self 的子字符串,否則返回 nil :
'foo'['oo'] # => "oo"
'foo'['xx'] # => nil
String#slice 是 String#[] 的別名。
相關用法
- Ruby String.slice!用法及代碼示例
- Ruby String.scan用法及代碼示例
- Ruby String.size用法及代碼示例
- Ruby String.scrub用法及代碼示例
- Ruby String.string <=>用法及代碼示例
- Ruby String.swapcase用法及代碼示例
- Ruby String.setbyte用法及代碼示例
- Ruby String.swapcase!用法及代碼示例
- Ruby String.start_with?用法及代碼示例
- Ruby String.string << object用法及代碼示例
- Ruby String.scrub!用法及代碼示例
- Ruby String.string + other_string用法及代碼示例
- Ruby String.string =~ regexp用法及代碼示例
- Ruby String.split用法及代碼示例
- Ruby String.squeeze用法及代碼示例
- Ruby String.succ用法及代碼示例
- Ruby String.string % object用法及代碼示例
- Ruby String.strip!用法及代碼示例
- Ruby String.string ===用法及代碼示例
- Ruby String.strip用法及代碼示例
- Ruby String.string ==用法及代碼示例
- Ruby String.string[index]用法及代碼示例
- Ruby String.string * integer用法及代碼示例
- Ruby String.match?用法及代碼示例
- Ruby String.unpack用法及代碼示例
注:本文由純淨天空篩選整理自ruby-lang.org大神的英文原創作品 String.slice。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
