Ruby Basics Flashcards
An edge case is…
something outside of the expected normal input
Give an example of string interpolation
name = “tina”
puts “my name is #{name}”
=>my name is tina
How do we get a hash value?
furniture[“name”]
=>”bed”
Most straight forward way of creating a hash
furniture = {“name” => “bed”, “colour” => “brown”, “material” => “wood”}
How do we add or change data in a hash?
to add new key and value:
furniture[“size”] = “king size”
to change value is same approach:
furniture[“size”] = “double”
How do we define a method in ruby?
def method() end
what does ‘gets’ do?
get string waits for user to make a keyboard input and passes it to the program
what does .chomp do?
removes the carriage return characters at the end of a string in such cases as after using ‘gets’
Constants are declared by…
Capitalizing every letter
Global variables are declared using which symbol?
$variable #usually avoided in ruby as can cause problems
Class variables are declared using which symbols?
@@class_variable
Class variables must be initialized at…
Class level, outside of method definitions
Instance variables are declared using which symbol?
@instance_variable
How do we type ‘else if’ in Ruby?
elsif
Opposite of if?
unless
Short hand for if else
? :
Loop takes a block denoted by..
{ } or do….end and loops it.
Name 2 ways of ending a loop
Break and Return
To skip an iteration in a loop we can use..
next
The opposite of a while loop is an
until loop
what does range do?
captures a range of elements i.e
1..5
=> 1,2,3,4,5
Methods that loop over a given set of data, allowing you to operate within each element in the collection
Iterators
Lines of code that are ready to be executed, contained within { } or do and end are called
Blocks
Recursion is the act of…
calling a method from within itself
.first
finds the first element from an array
.last
finds the last element in an array
.pop
removes the last element from an array and returns it
(this method mutates the caller)`
what is the shortcut for the push method?
array«
also known as shovel
.push
adds element to the end of an array
mutates the caller
.map and .collect
iterate over a collection applying a block to each element in the collection, then returning a new collection.
.delete_at
takes an array index and deletes the corresponding array item without leaving a gap
.delete
takes a value and deletes the corresponding array item(s)
.uniq
finds duplicates within an array and returns a new array with duplicates removed
.select
returns all elements in a collection that return true to the conditions that you specify
What does the bang operator (!) after a method usually signify?
that it will mutate the caller
.unshift
adds a specified value to the start of an array
.include?
checks if an argument given is included in the array
? after a method usually indicates?
that it will return a boolean value.
.flatten
converts a nested array into a normal array
.eachindex
passes the index of an array element rather than a value into the block
.each_with_index
passes both index and value of array element to the block
.sort
returns a sorted array
What is the difference between .each and .map?`
each discards the return value making no changes whereas map creates a new array from its return value
What is a class?
Basically a custom data type that you can create
What is the setter/getter syntax for classes?
attr-accessor
Putting a : before anything defines it as what?
Symbol
Multi line comment
=begin
=end
What’s the difference between anIntegerand aFloat?
Integer is a whole number, float has a decimal
What’s the difference between==, and===?
== is a comparison operator, whereas === typically asks whether the thing on the right is of the same type or is a member of the thing on the left.
How do you do exponents in Ruby?
x**y (x to the power of y)
What’s the difference between(1..3)and(1…3)?
(1..3) includes 1 and 3 whereas (1…3) excludes 3
What are three ways to create a range?
1..10
1…11
Range.new(start, finish)
What’s the difference between single and double quotes?
Nothing apart from you should only use string interpolation inside double quotes and if you need to use quotes within quotes then use single inside doubles.
What are escape characters?
Escape characters () waiver characters and meta characters from acting how they would normally, escaping their function I.e “my name is #{name}” => “my name is #{name}”
What are line breaks?
code used to create a new line in the terminal i.e (\n)
How do you make other things into strings?
to_s
How do you concatenate strings?
“like ” + “ this”
“like”.+(“this”)
How do you access a specific character or substring?
By treating it like an array: s = “hello”
s[0]
=> “h”
s[-1]
=> “o”
s[1..-2]
=> “ell”
How do you split up strings into arrays?
split()
How do you get and clean up user input on the command line?
gets.chomp
What does it mean that strings are “mutable” and why care?
Mutable objects can be added to, reversed and messed around with in 100 different ways. Immutable objects such as symbols cannot be changed, which is why they make good hash keys.
What is a symbol?
A symbol is like a string but with no depth. It is immutable so it cannot be changed, and is perfect for use as names that don’t need to change such as in hash keys. It is denoted as follows :symbol
What is a Regular Expression (RegEx)?
Regex is a special syntax used to find things
How can you center or right-justify a string?
center() and .rjust()
What are three ways to create an array?
a = Array.new b = [] c = Array[]
How do you pre-populate an array with default data?
full_array = Array.new(3, “hi”) => [“hi”, “hi”, “hi”]
How can you access a specific group of items in an array?
array = [1, 3, 5, 7, 2]
array[0] => 1, array[-1] => 2, array[1..3] => [3,5,7]
How do you modify the items in an array?
Same as accessing them, except an assignment operator is used: array[0] = 2
How do you combine arrays?
Similar to strings, you use the + operator
How do you find the values in one array that aren’t in another?
by using subtract
[1,6,3,4] - [1,6,3,5] => [4] (note the 5 is not returned because it is on the right hand side)
How do you find duplicate values in 2 arrays?
by using ampersand
[1,2,3] & [2,4,5] => [2]
What is the difference betweenpush/popandshift/unshift?
push and pop deal with the end of an array; adding and removing the last element, whereas shift and unshift deal with the beginning of an array; adding and removing the first element.
How is arr.popdifferent from arr[-1]?
Arr.pop removes the last item of an array before returning it, whereas arr[-1] just returns it.
How ispushing or«_space;ing another array into your array different from just adding them together?
Pushing an array into your array will create a nested array whereas adding an array will just add to it.
Why should you be careful deleting items in an array?
Because it will change the index of all the other items after it, which must be considered for things like loops etc.
How can you convert arrays to strings?
join()
How can you convert from other data types to arrays?
to_a
How do you find the biggest item in an array?
max
How do you find the smallest item in an array?
min
How do you find out how big an array is?
size
How do you put an array in order?
sort
What are the naming conventions for arrays?
Always use plurals and be descriptive
What is a hash?
A container for data, like arrays, but instead of storing data based on numeric indices, you use “keys” which can be strings or symbols. This makes hashes more appropriate for storing data with a bit more depth to it.
What are keys and values?
keys are a named address of a corresponding value that is stored, i.e. key: “name” value: “john”
How is a hash different from an array?
They are different in that a hash is not stored in any order and hashes are declared with curly braces instead of square brackets.
What are 2 ways to create a hash?
my_hash = Hash.new my_hash = {},
What are options hashes?
they are parameters passed to a method in a hash
How do you delete data from a hash?
Deletefrom a hash by just setting the value tonilor by using thedeletemethod
How do you add hashes together?
hash1.merge(hash2)
How do you list out all the keys or values?
Use the .keys or .values method
How do you see if the hash contains a key or value?
has_key?() has_value?()
What is a set?
A simpler kind of hash is called aset, and it’s just a hash where all the values are either True or False. It’s useful because your computer can search more quickly through this than an array
How do you get the current date and time?
by creating a time object – Time.new or Time.now
How do you find just the Year? Month? Hour? Second? Weekday?
by using .year, .month, .hour, .second, or .wday method on a time object
How do you create aTimespecifically for 12/25/2013?
Time.new(year, month, day, hour, min, sec, time_zone_offset_from_utc)
How do you find how many days have passed between twoTime’s?
by simply subtracting one from another
How would you find out the time that was 100 seconds ago? 10 days ago?
By subtracting the seconds i.e.
Time.now - 100
What isnil?
nil represents literally nothing and is the absence of value
How do you check if something isnil?
nil?
What’s the difference betweenputsandpandprint?
Print runs the .to_s method whilst puts also does this but adds a new line after it. P runs the .inspect method which returns more information than print and puts.
What doesinspectdo?
Returns a string containing a human-readable representation ofobj. The defaultinspect shows the object’s class name, an encoding of the object id, and a list of the instance variables and their values (by callinginspecton each of them).
What do+=,-=,*=and/=do?
a += bis the same asa = a + b
a -= bis the same asa = a – b
a *= bis the same asa = a * b
a /= bis the same asa = a / b
What is parallel assignment?
is when you assign the values of more than one variable at a time i.e: a, b = 1, "hi" a => 1 b => “hi”
What’s the easiest way to swap two variables?
By using parallel assignment i.e.
a,b = b,a
What does the gsub method do?
gsub(pattern, replacement)
global substitute, a string method that takes a pattern such as regex or a string in the 1st parameter, finds it and replaces it with the 2nd parameter
What is a “boolean”?
A data type with only 2 possible values; true and false
What are “truthy” values?
In Ruby, it’s simple: nil and false are false and that’s it. Everything else is “truthy”.
What does <=> do?
The ‘spaceship’ operator gives three different possible outputs (1, 0 or -1) depending on whether the left side is greater than, less than, or equal to the right side.
What is a “boolean”?
A value of either true or false
What are “truthy” values?
Anything that is not nil or false is a truthy value
Are nil, 0, “0”, “”, 1, [], {} and -1 considered true or false?
All true except for nil.
What do || and && and ! do?
Or, And, Not respectively.
What is ||=?
it basically expands to thing_a || thing_a = thing_b. So if thing_a hasn’t been set to anything, it becomes thing_b, otherwise it keeps its original value.
What is the ternary operator?
condition ? do_this_if_true : do_this_if_false
When should you use a case statement?
For situations where you’re just checking to see if something equals any one of a number of clear but different options, a case statement can be a good substitute instead of If.
What is an index variable?
This is used in a loop to keep track of which iteration you are on or to otherwise increment until a condition is reached
How do you stop a loop?
break
How do you skip to the next iteration of a loop?
next
How would you start a loop over again?
redo will let you restart the loop (without evaluating the condition on the first go-through), usually with some condition
What does nesting loops mean and when would you use it?
Nesting loops occurs when one goes inside another, so you execute the entire inner loop for each iteration of the outer loop. Often used for “two-dimensional” problems, like searching through arrays within arrays.
How is a block like a function?
Blocks are often called “anonymous functions” because they have no name but behave much like functions. They’re like little helper functions… you don’t find blocks just hanging around without some method (like #each) using them.
What are the two ways to declare a block?
{ } or do…end
How do you return data from a block?
Implicitly. So whatever is on the last line of the block is returned. You cannot use ‘return’.
What happens if you include a return statement in a block?
This will return you from whatever method actually called the block, which is bad.
What does yield do?
Yield allows a method to run a block from outside the method
How do you pass arguments to a block from within a method?
yield(argument)
How do you check whether a block was actually passed in?
block_given?, or rather: yield if block_given?
What is a proc?
A Proc is just a block that you save to a variable, thereby giving it a bit more permanence
What’s the difference between a proc and a block?
Procs are objects, blocks are not. You can pass multiple procs to methods, whereas you can only pass one block to a method.
What is a closure?
A closure is a function that: 1. can be passed around as a variable and 2. binds to the same scope in which it was created; Similar to a suitcase, it’s a group of code that when opened (i.e. called), contains whatever was in it when you packed it (i.e. created it).
What is a lambda?
A lambda is similar to a proc except it checks the number of arguments it is passed is correct.
Lambdas will only return from the lambda itself and not the enclosing method, which is what happens if you use return inside a block or Proc.
What is a Method (capital “M”)?
Method’s (capitalized because they’re actually a class of their own) are really just a convenient way to pass a normal method to another normal method by wrapping the symbol of its name in the word method()
What is a module?
Ruby Modules are similar to classes in that they hold a collection of methods, constants, and other module and class definitions.
Why are modules useful?
they allow you to share functionality between classes - if a class mixes in a module, that module’s instance methods become available as if they had been defined in the class.
What does inject do?
inject or reduce passes not just the element but also whatever was returned by the previous iteration into the block.
How do you check if every item in a hash fulfills a certain criteria?
all?
What (basically) is an enumerator?
A class which allows both internal and external iteration.
How many things should a method ideally do?
One. If it’s doing two, it’s time for another method. If it’s doing a dozen, you probably need to start thinking about having a separate class.
What does self mean?
it refers to whatever object the current method was called on (the “caller”). So if I called current_user.jump, current_user is the caller of that method. Inside the definition of the #jump method, self would refer to the current_user.
What do you need to do to create your own Ruby script file?
Just save your file with a .rb extension