Basics Flashcards
2-D hash Iteration, print key and value
secret_identities = { "The Batman" => "Bruce Wayne", "Superman" => "Clark Kent", "Wonder Woman" => "Diana Prince", "Freakazoid" => "Dexter Douglas" }
secret_identities.each { |key, value| puts “#{key}: #{value}”}
Declare hash literally
hash = { key1 => value1,
key2 => value2,
key3 => value3
}
Declare hash using “new” keyword
my_array = Hash.new
note: “Hash” must be capitalized.
Add element to hash declared literally
pets = Hash.new pets["Donder"] = "dog"
Access value in hash using keyword
pets[“Stevie”]
will return “cat”
Iteration through array
languages = [“HTML”, “CSS”, “JavaScript”, “Python”, “Ruby”]
languages.each{ |x| puts “#{x}” }
If statement
if 5 == 5
print “Yes, it does”
end
Else
if 5 == 5 print "Yes, it does" else print "What a strange world." end
Elsif
puts "Choose a number" number = Integer(gets.chomp) if number == 5 print "Yes, it does" elsif number > 5 print "Hmmm" else print "What a strange world." end
Unless
hungry = false
unless hungry puts "I'm writing Ruby programs!" else puts "Time to eat!" end
Get input from user
variable_name = gets.chomp
chomp eliminates newline character
Split method
puts “Please enter a string…”
text = gets.chomp
words = text.split
creates an array out of string
Sort_By Method
h = h.sort_by {|a, b| b }
# the hash h will be sorted by increasing order of b, or the value of each # key-value pair
Reverse Method
.reverse!
Define a method
def welcome
puts “Welcome to Ruby!”
end