Syntax

Types

Code ExampleDescriptionOutput
'Hi all!'string literal"Hi all!"
375integer literal375
3.141528float literal3.141528
trueboolean literaltrue
{ 'a' => 1, 'b' => 2 }hash literal{"a" => 1, "b" => 2}
[ 1, 2, 3 ]array literal[1, 2, 3]
:symsymbol literal:sym
nilnil literalnil

Casting

Code ExampleDescriptionOutput
13.to_fconvert to float13.0
13.0.to_iconvert to integer13
5.to_sconvert to string"5"
5.to_aconvert to array[5]
5.to_hconvert to hash{5 => nil}

String Methods

Code ExampleDescriptionOutput
"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".capitalizecapitalize the first letter"Hi"
"[1, 2, 3].join("-") joins array into string1-2-3
"hi".include?("i")checks if substring is includedtrue
"hi".upcaseconvert to uppercase"HI"
"Hi".downcaseconvert to lowercase"hi"
"hi".empty?checks if string is emptyfalse
"hi".lengthlength of the string2
"hi".reversereverse the string"ih"
"hi all".splitsplit by whitespace["hi", "all"]
"hi".split("")split into characters["h", "i"]
" hi, all ".stripremove 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 ExampleDescriptionOutput
[1, 2, 3, 4, 5].firstfirst element of the array1
[1, 2, 3, 4, 5].lastlast element of the array5
[1, 2, 3, 4, 5].lengthlength of the array5
[1, 2, 3].push(4)add element to end[1, 2, 3, 4]
[1, 2, 3, 4].pop(2)remove last 2 elements3, 4
[1, 2, 3].unshift(0)add element to the beginning[0, 1, 2, 3]
[0, 1, 2, 3].shiftremove first element0
[0, 1].any? { |num| num > 5 }check if any meet conditionfalse
[0, 1].all? { |num| num > 5 }check if all meet conditionfalse
[0, 1].none? { |num| num > 5 }check if none meet conditiontrue
[1,[2, [3, 4]]].flattenflatten nested arrays[1, 2, 3, 4]