April 2015 Flashcards
PEMDAS. What is the sentence behind this acronym?
Please Excuse My Dear Aunt Sally
Parentheses, Exponents, Multiplication, Division, Addition, Subtraction
RUBY
What is the meaning of the unless keyword in ruby?
unless age >= 18
if age < 18
Ruby
how to write an infinite loop?
loop do
expression
end
Ruby
Write a for loop which executes an expression 5 times
5.times do
expression
end
Ruby
Is it allowed to have arrays that contain object of different types?
yes!
Ruby
How can I add the string “foo” to the array [1,2,3]
[1,2,3].push(“foo”) or
[1,2,3] «_space;“foo”
Ruby
Multiply every element in the array [1,2,3] by 3 using the map
[1,2,3].map { |i| i*3}
Ruby
Filter the even numbers from the array [1,2,3,4] using select
[1,2,3,4].select { |number| number % 2 == 0 }
Ruby
How can I loop over the array [1,2,3] with each
[1,2,3].each do |number|
new_array «_space;number
end
Ruby
Create a hash map with some strings as keys and some integers as values
my_map = {“key1” => 1, “key2” => 2}
Ruby
Given the map my_map = {“key1” => 1, “key2” => 2}, retrieve the value of the “key1”
my_map[“key1”]
returns 1
Ruby How to get the class of an object? For example get the class of object 1
1.class returns FIXUM (a special kind of integer)
Ruby
check if 1 is of type Integer
1.is_a?(Integer)
Ruby
Write a method that adds 2 to a number
def add_two(number)
number.next.next
end
Ruby
How to define a function with unknown number of parameters?
Using the splat operator which is a *
def my_function(*argument)
end
Ruby
add an option to the add(num1,num2) that returns the absolute value if the option is true
def add(num1, num2, options = {}) sum = num1 + num2 sum = sum.abs if options[:absolute] end
Ruby
Define a single line lambda that returns a string
l = lambda {“foo bar”}
puts l.call
Ruby
Define a multiline lambda with an argument. If argument is “try” print something and else, print something else
l = lamda do |input| if string== "try" return "foo" else return "bar" end puts l.call("try")