String
8 methodsA String object holds and manipulates an arbitrary sequence of bytes, typically representing characters.
String#length -> IntegerReturns the number of characters in the string.
Returns
Integer
Example
"hello".length # 5
"日本語".length # 3String#upcase -> StringReturns a copy of str with all lowercase letters replaced with their uppercase counterparts.
Returns
String
Example
"hello World".upcase # "HELLO WORLD"String#downcase -> StringReturns a copy of str with all uppercase letters replaced with their lowercase counterparts.
Returns
String
Example
"HELLO World".downcase # "hello world"String#split(pattern=nil, [limit]) -> ArrayDivides str into substrings based on a delimiter, returning an array of substrings.
Parameters
| Name | Type | Description |
|---|---|---|
| pattern | Regexp|String|nil | Delimiter pattern. nil splits on whitespace. |
| limit | Integer | Optional limit on number of splits. |
Returns
Array
Example
"a,b,c".split(",") # ["a", "b", "c"]
" hello world ".split # ["hello", "world"]
"a-b-c".split("-", 2) # ["a", "b-c"]String#gsub(pattern, replacement) -> StringReturns a copy of str with all occurrences of pattern substituted with replacement.
Parameters
| Name | Type | Description |
|---|---|---|
| pattern | Regexp|String | Pattern to match. |
| replacement | String|Hash | Replacement string or mapping. |
Returns
String
Example
"hello world".gsub("o", "0") # "hell0 w0rld"
"2024-01-01".gsub("-", "/") # "2024/01/01"String#strip -> StringReturns a copy of str with leading and trailing whitespace removed.
Returns
String
Example
" hello ".strip # "hello"String#include?(substring) -> boolReturns true if str contains the given string or character.
Parameters
| Name | Type | Description |
|---|---|---|
| substring | String | Substring to check for. |
Returns
Boolean
Example
"hello world".include?("world") # true
"hello".include?("z") # falseString#chars -> ArrayReturns an array of characters in str.
Returns
Array
Example
"hello".chars # ["h", "e", "l", "l", "o"]