Refactoring Flashcards

You may prefer our related Brainscape-certified flashcards:
1
Q

If an if statement in Ruby is a short simple expression, how could you write it, and also write one using the keyword unless and using a ternary operator?

A

age = 18
puts “You’re a big boy!” if age >= 18

Or

age = 3
puts “You’re a big boy” unless age < 18

Or

age = 18
puts age >= 18? “You can drive!” : “You can’t”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How would you refactor the following code?

case language
  when "JS"
    puts "Websites!"
  when "Python"
    puts "Science!"
  when "Ruby"
    puts "Web apps!"
  else
    puts "I don't know!"
end
A

language = “JS”

case language
when "JS" then puts "Websites!"
when "Python" then puts "Science!"
when "Ruby" then puts "Web apps!"
else "I don't know!"
end
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

We can use the = to assign values to variables, but if we want to only assign a value if it doesn’t have one?

A

favorite_book = nil;

favorite_book ||=
puts “I like turtles!”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

If you write in a method in Ruby, do you have to use a return statement, and if so give an example?

A

def legal_driver (n)
n % 3 == 0? “True” : “False”
end

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Write a quicker/easier way to loop through each item in the array my_array only shows the number in the console if even

my_array = [3, 7, 2]

A

my_array = [3, 7, 2]

my_array.each { |n| puts n if n % 2 ==0 }

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Whats an awesome shortcut instead of using .push and what else can you use it on other than arrays?

A

groceries = [“orange’”] &laquo_space;“apple”

name = “Scott” &laquo_space;“Bartels”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

When you use a refactored case statement in the case statement there is only comparison operator you can use, what is this? Write a example using it too.

A

puts “Enter age: “
age = gets.chomp.to_i

case age
when 1..3 then puts "Baby!"
when 4..12 then puts "Kid!"
when 13..17 then puts "Teen!"
else
if (age >= 18)
puts "You can drive yesss, also Adult!"
end
end
How well did you know this?
1
Not at all
2
3
4
5
Perfectly