Getting to know Ruby Flashcards
Wat would be an example of a UNLESS control statement?
unless x == true
do this
end

What would be a WHILE control
x = 10
while x > 9
puts x
x -= 1
end

What would be an example of an UNTILL statement?
x = 10
untill x == 5
puts “x is true “
x -= 5
end

besides ittarations with .each or .times, what flow method is often used in other languages?
The for loop!
Although ruby has it, there are smarter alternatives.
for x in 1..10
puts x
end

Describe a CASE statement, as if it was an IF statement.
age 23
case
when age >= 23
puts “drink”
when age <= 23
puts “dont drink!”
else
puts “think ab out it.. there is no else..”
end

A CASE statement, that internaly uses ‘===’
‘if this then that’
That is, the string litural comparrison or a superset equal comparrison. And littuarly compares trough conversion.
name = “Fisher”
case name
when /fish/i then puts “Somethings fishy”
when ‘Smith’ then puts “Your name is smith”
end

The IF else Statement is declares as follows:
if x == true
p “x is true”
elseif y == true
p “ y is true “
else
p “everything else is true”
end

Shorthand oneliner for 2 variables?
puts “good!” if a == true and b == true

a shorthand oneliner while loop?
times_2 = 2
times_2 *= 2 while times_2 < 100

What is the difference between a function, and a method?
What do they have in common?
Function is defined outside of a class.
Method is defined inside of a class.
They’ll both always belong to a class.
Describe characteristics of a Method/Function.
Ex: How is it written?
- parantheses are optional
- no need for type declaration
- can return whateffer you want
- return is optional
- last evaluation will be returnd
Describe a Predictive Method.
A Prediective Method is declared by appending the “?”, and will evaluate upon what it is called to either true or false.
It can take arguments.
def is_a_number ?(number)
return false if !number.not_a?(number)
true
end
puts is_a_number? 3
true

How can you implement a Default Value for a method argument?
def method_with_default( n = 5 )
n % 5
end
puts method_with_default(4)
=\> 20 puts method\_with\_default #=\> 25

What is the use of the Splat operator?
How would it be implemented in a Method Argument?
- Splat operator takes any number of arguments and stores them into an array.
- the splat operator can also be a ‘middle’ argument, as shown below.
def method_with_arguments( first, *middle, last)
puts middle.max
end
puts method_with_arguments(“Hi”, 4, 432, 2, “bye”)
=> ‘432’

What is a ‘block’ ? And what is it’s use?
- Blocks are chunks of code, that are being executed by a Method or Function.
- They are often used as itterators
- can be declared with oneliner: { puts “this” }
- can be declared with do - end
do
puts “this
end - can Implicit or Explicit
How would you call a Block, that prints “Hi” 5 times?
5.times { puts “Hi” }
or
- times do | greet |
greet. puts “hi”
end

Write an Implicit block,
- that yields twice
- if block_given? is True
- else returns “No block”
def two_times_implicit
return “No block” unless block_given?
yield
yield
end

Write an Explicit block
- calls twice if block is given
- or returns “No block” if not
def explicit_block(&this_block)
return “No block” if this_block.nill?
this_block.call
this_block.call
end

What is between the pipe ( | paramater | ) characters if you declare a block?
How about the block parameter?

Write a method reading ‘text.txt’, that puts it out.
Try escaping line characters.
File.read(‘text.txt’) do | line |
puts line.chomp
end

Write a method to write to the ‘text.txt’ file.
- Any line will do.
- what extra attention do you have to be aware of?
you’ll have to give the Class.method (File.open) the argument to “w” short for “write” to the file..
File.open(“text.txt”, “w”) do | line |
line.puts “Hi there”
end

Open the file ‘text.txt’ if it exists.
Write a Predictive method to do so, and put out the lines.
if File.exist?(‘text.txt’)
File.read(‘text.txt’) do | line |
puts line.chomp
end
end

How would you handle an error..
if for example a file doesnt excist?
best practise is to use a cycle of
begin - rescue - end.
the ‘rescue’ catches the Eceptions witch then can be assigned to a variable.
begin
File.foreach(‘not-exist’) do | line |
puts “doesnt matter..”
end
rescue Exception => e
puts e.message
puts “lets pretend that diddn’t happend”
end
end
end

How would you puts your enviroment varaible stating what editor you use?
puts ENV[“editor”]
=> “Sublime text 3 offcourse”

make ‘x’ a range from 1 upto 100
x = 1…100

What method can u use to select Elements of an array
new_array = a.select { |num| num < 4 }

Can you Chain multiple methods on an array?
example: .select . reject
You shure can!
a = [1.. 10].to_a
b = a.select { |x| x >5 }.reject { |v| v.even? }

What method itterattes over an Array,
and modifyes it by 3 if the block is {|x| x*3} ?
a.map{ | x | x * 3 }

Range the letters of the alfabet, and pick 2.
place them in a new variable.
bonus points for a oneline!
a = (‘a’..’z’)
new_variable = a.sample(2)
new_variable = (‘a’..’z’).to_a.sample(2)

Given the age, make a case statement using a range.
devide in upto 44 and above till 110.
age = 44
case age
when <= 0..44
puts “youngster
when > 44..110
puts “oldtimer”
else
p “no age!”
end

What is ment by ‘hetrogeneous’ arrays?
It can hold more then one type of element in the array.
example,
hetro_array = [“1”, two, :tree, 5]
What method can be used to chop a string
into a array of sperate words?
%w{ this is a string ! }

Given a string, ex: “Hello”
Grep the methods containing ‘case’
in the name.
p “Hello”.methods.grep /case/

Storing ellements in an Array: Last in, first out.
LIFO! aka ‘stacking’ elements.
What two ways of adding do you know?
What ways of removing elements do you know?
stack = []
stack.push “one”
stack << “two”
stack. pop
* # => “two”*

FIFO aka Qeuing,
First in, First out
How can you add an element?
How can you remove an element?
que = []
que.push “one”
que << “two”
que. shift
* # => one*

a = [1,2,3,4]
Itterate over a, print it out and add 2.
a.each { | x | puts “#{x +2 } “ }

Can you create an Array of a range?
Shure can!
array_from_range = (1..199).to_a
Create method adjust_colors, witch has
a named paramether ‘props’, beeing
a hash holding forground and background colours.
The color can be any colour you like.
def adjust_colours( props = { foreground: “Blue, background: “Black” } )
end

Given the method: adjust_colours,
what would be the output of calling it withour arguments?

#=\> foreground: red #=\> background: white

given the method: adjust_colors,
how do you adjust the background propertie?

adjust_color( { background: “new option” } )
or if it’s single case,
adjust_color backgroudnd: “new option”
Although not common: puts hash
can give an error!
Why? And how to prevent this?
Because it sees the hash as a block!
You can use parantheses to precent it,
like: print( { first: “Hi”, second: “Bye” } )
How do you assing a hash with the hashrocket?
hash = { first => “this”, last => “that” }

A hash contains 4 elements,
Can you set element 6 to be “beer” ?
if so, what becomes element 5?
element[6]= “beer”
element => [1,2,3,4,nil,”beer”]

What method can you use to itterate over a Hash?
you’ll use: each_pair
ex: [1: “first”, 2: “second”].each_pair do | key, value |

beers is a Hash that contains a lot
of beers, can you print them out?
bonus points for a oneliner!
beers.each_pair do | key, value|
puts “#{key} holds #{value} “
end
beers.each_pair { |k,v| puts “#{k} holds #{v}” }

Can a hash have a devault value ?
Yes, example:
word_count = Hash.new(0)
each value gets default 0, keys are set bij the element.
Can you make a word counter?
Given a sentence: “Beer for booba beer bo”
word_counter = Hash.new(0)
sentence.split.each do |word|
word_counter[word.downcase] += 1
end
