Syntax
Types
Code Example | Description | Output |
---|---|---|
'Hi all!' | string literal | "Hi all!" |
375 | integer literal | 375 |
3.141528 | float literal | 3.141528 |
true | boolean literal | true |
{ 'a' => 1, 'b' => 2 } | hash literal | {"a" => 1, "b" => 2} |
[ 1, 2, 3 ] | array literal | [1, 2, 3] |
:sym | symbol literal | :sym |
nil | nil literal | nil |
Casting
Code Example | Description | Output |
---|---|---|
13.to_f | convert to float | 13.0 |
13.0.to_i | convert to integer | 13 |
5.to_s | convert to string | "5" |
5.to_a | convert to array | [5] |
5.to_h | convert to hash | {5 => nil} |
String Methods
Code Example | Description | Output |
---|---|---|
"hi"[0] | first character of the string | "h" |
"hi"[0..1] | substring from index 0 to 1 | "hi" |
"hi"[0, 2] | substring from index 0, length 2 | "hi" |
"hi"[-1] | last character of the string | "i" |
name = "bob"; "hi #{name}" | string interpolation | "hi bob" |
"hi".capitalize | capitalize the first letter | "Hi" |
"[1, 2, 3].join("-") | joins array into string | 1-2-3 |
"hi".include?("i") | checks if substring is included | true |
"hi".upcase | convert to uppercase | "HI" |
"Hi".downcase | convert to lowercase | "hi" |
"hi".empty? | checks if string is empty | false |
"hi".length | length of the string | 2 |
"hi".reverse | reverse the string | "ih" |
"hi all".split | split by whitespace | ["hi", "all"] |
"hi".split("") | split into characters | ["h", "i"] |
" hi, all ".strip | remove leading/trailing spaces | "hi, all" |
"he77o".sub("7", "l") | replace first β7β with βlβ | "hel7o" |
"he77o".gsub("7", "l") | replace all β7β with βlβ | "hello" |
"hi".insert(-1, " dude") | insert substring at index | "hi dude" |
"hi all".delete("l") | delete all βlβ | "hi a" |
"!".prepend("hi, ", "all") | prepend strings | "hi, all!" |
Array Methods
Code Example | Description | Output |
---|---|---|
[1, 2, 3, 4, 5].first | first element of the array | 1 |
[1, 2, 3, 4, 5].last | last element of the array | 5 |
[1, 2, 3, 4, 5].length | length of the array | 5 |
[1, 2, 3].push(4) | add element to end | [1, 2, 3, 4] |
[1, 2, 3, 4].pop(2) | remove last 2 elements | 3, 4 |
[1, 2, 3].unshift(0) | add element to the beginning | [0, 1, 2, 3] |
[0, 1, 2, 3].shift | remove first element | 0 |
[0, 1].any? { |num| num > 5 } | check if any meet condition | false |
[0, 1].all? { |num| num > 5 } | check if all meet condition | false |
[0, 1].none? { |num| num > 5 } | check if none meet condition | true |
[1,[2, [3, 4]]].flatten | flatten nested arrays | [1, 2, 3, 4] |