Ruby Flashcards
What are some basic classes?
Fixnum
String
Array
Hash
How to get user input?
input = gets.chomp // chomp removes \n
How to convert string to int and int to string?
string.to_i and int.to_s
Method and constructor format?
def initialize // a constructor w/o params // code end
def initialize(name, age) // a constructor w params // code end
A class with class and instance variables? Also define a sub class?
class MyClass @instanceVariable @@classVariable
def myMethod
localVariable = 2
end
end
class MySubClass
what is the spaceship operator?
a b
// resutls in a b = 1
Array Syntax?
animals = Array.new animals = ["bear", "dog", "cat"] animals[0] // bear animals[0] = 1 animals[0] // 1
arr[:slot1, :slot2, :slot3]
:slot1 // arr[0]
Iterate over array?
arr.each { |x| puts x }
Null in Ruby?
nil
What is a block and are they first class citizens?
A function w/o a name.
3.times { |x| puts x}
block-> |—————|
A block cannot be assigned to a variable as it is not a first class citizen. So one must use a proc:
b = Proc.new { |x| puts x }
b.call(x)
How to use yield?
def test yield 5 end test { |x| puts x} // called when yield is called (also works w/o param)
A ruby while loop?
i = 0
while i
Define Ruby?
Object orientated
Interpreted
Dynamically typed
Strongly typed for the most part
How to evaluate a string before returning it?
One quote interprets string literraly
Double quotes evals string
x = 5
puts “Number: #{x}” // Number: 5
puts ‘Number: #{x}’ // Number: #{x}
Method parameter optional value with default value?
def myMethod(req, optional=1) // code end