• Shuffle
    Toggle On
    Toggle Off
  • Alphabetize
    Toggle On
    Toggle Off
  • Front First
    Toggle On
    Toggle Off
  • Both Sides
    Toggle On
    Toggle Off
  • Read
    Toggle On
    Toggle Off
Reading...
Front

Card Range To Study

through

image

Play button

image

Play button

image

Progress

1/10

Click to flip

Use LEFT and RIGHT arrow keys to navigate between flashcards;

Use UP and DOWN arrow keys to flip the card;

H to show hint;

A reads text to speech;

10 Cards in this Set

  • Front
  • Back

Write a method that takes two arguments, a string and a positive integer, and prints the string as many times as the integer indicates.


repeat('Hello', 3)


Output:


Hello

Hello

Hello

  When solving exercises, it can be beneficial to progress in small increments. We started out by defining repeat with two parameters. Then, to ensure everything worked properly, we added puts string inside the method and ran the code.


def repea...


When solving exercises, it can be beneficial to progress in small increments. We started out by defining repeat with two parameters. Then, to ensure everything worked properly, we added puts string inside the method and ran the code.




def repeat(string, number) puts stringend




This works correctly, however, it only prints string once. Our goal is to print string a specified number of times. One of the more suitable methods for this situation is Integer#times. Using this method, we can execute puts string any number of times. In this case, we want to print string the number of times indicated by number.

Write a method that takes one argument in the form of an integer or a float; this argument may be either positive or negative. This method should check if a number is odd, returning true if its absolute value is odd. You may assume that only integers are passed in as arguments.


puts is_odd?(2) # => false

puts is_odd?(5) # => true

puts is_odd?(-17) # => true

puts is_odd?(-8) # => false


Keep in mind that you're not allowed to use #odd? or #even? in your solution.

To determine if a number is odd without using #odd? or #even?, we just need to check if the number modulo 2 is 1. In ruby, we use the % to perform modulus operations, so we use it here to determine whether the number is odd.


Further Exploration
...

To determine if a number is odd without using #odd? or #even?, we just need to check if the number modulo 2 is 1. In ruby, we use the % to perform modulus operations, so we use it here to determine whether the number is odd.




Further Exploration


This solution relies on the fact that % is the modulus operator in Ruby, not a remainder operator like it is in some other languages. Remainder operators can return negative results if the number on the left is negative, while modulus always returns a non-negative result if the number on the right is positive. If you weren't certain whether % were the modulus or remainder operator, how would you rewrite #is_odd? so it worked regardless?

Write a method that takes one argument, a positive integer, and returns a list of the digits in the number.Examples:


puts digit_list(12345) == [1, 2, 3, 4, 5]

puts digit_list(7) == [7]

puts digit_list(375290) == [3, 7, 5, 2, 9, 0]

puts digit_list(444) == [4, 4, 4]


All of the tests above should print true.

Idiomatic Ruby:
def digit_list(number)  number.to_s.chars.map(&:to_i) 
end


  The brute force approach (which is not a derogatory term) simply chops off digits from the beginning of the number one at a time, adding them to an array, then returns ...

Idiomatic Ruby:


def digit_list(number) number.to_s.chars.map(&:to_i)


end




The brute force approach (which is not a derogatory term) simply chops off digits from the beginning of the number one at a time, adding them to an array, then returns the array. The tricky part of this loop is the use of Fixnum#divmod which divides number by 10, and returns two values: the result of performing an integer division, and the remainder. For example, 12345.divmod(10) returns [1234, 5]. This has the advantage of being easy to understand.




A more Ruby-inclined way of approaching this problem is in the second solution. This is somewhat dense, but it's very typical of the code you'll encounter (and write!) in Ruby all the time. Let's break it down.




Our goal is to convert a number to a list of its digits. The easiest way to do this is to first convert the number to a string, then split the resulting string. This gives us an array of characters, each of which represents one digit. This is almost what we want, but we need to return an array of numbers, not an array of strings. That's where Enumerable#map comes to the rescue. You might find the (&:to_i)part weird, but this is Ruby syntactic sugar; it's shorthand for:




something.map {|char|char.to_i}

Write a method that counts the number of occurrences of each element in a given array.




vehicles = ['car', 'car', 'truck', 'car', 'SUV', 'truck', 'motorcycle', 'motorcycle', 'car', 'truck']


count_occurrences(vehicles)



Once counted, print each element alongside the number of occurrences. Expected output:



car => 4


truck =>


3SUV => 1


motorcycle => 2

sdgsdfgsdg

Write a method that takes one argument, a string, and returns the same string with the words in reverse order.




puts reverse_sentence('') == ''


puts reverse_sentence('Hello World') == 'World Hello'


puts reverse_sentence('Reverse these words') == 'words these Reverse'




The tests above should print true.

  To reverse the order of substrings within a string, we first need to separate those substrings. In our solution, we use #splitwith no arguments to separate each word and place it in an array. To reverse the order of the words, we then invoke ...

To reverse the order of substrings within a string, we first need to separate those substrings. In our solution, we use #splitwith no arguments to separate each word and place it in an array. To reverse the order of the words, we then invoke #reverseon the array. Now, string looks like this:


'Hello World'.split.reverse # => ["World", "Hello"]


That's exactly what we want except we need it to be a string, not an array. To accomplish this, we invoke #join which joins every element in an array using the given argument as the delimiter.

Write a method that takes one argument, a string containing one or more words, and returns the given string with all five or more letter words reversed. Each string will consist of only letters and spaces. Spaces should be included only when more than one word is present.




puts reverse_words('Professional') # => lanoisseforP


puts reverse_words('Walk around the block') # => Walk dnuora the kcolb


puts reverse_words('Launch School') # => hcnuaL loohcS



When given a string or an array, and asked to evaluate each character or element, your first instinct should be to reach for an iterator. Our goal here is to iterate over the given string and check each word for the number of characters it co...

When given a string or an array, and asked to evaluate each character or element, your first instinct should be to reach for an iterator. Our goal here is to iterate over the given string and check each word for the number of characters it contains. If it has five or more characters then we'll reverse the word.




At the top of our method, we create an empty array named words that will hold each modified word of the result: these words will be reversed if long, or as-is if they are short. We use #each to iterate over string, but first, we need to separate each word in string using #split, which returns an array containing the separated words. For each word, we count the number of characters it contains using #size. If it contains five or more characters, we use the destructive method #reverse! to reverse the word. We mutate word so that we can add it to words by invoking words << word.




After iterating over string and evaluating each word, words will contain all of the words, with longer words reversed. Finally, we can invoke words.join(' ') to return the desired string.

Write a method that takes one argument, a positive integer, and returns a string of alternating 1s and 0s, always starting with 1. The length of the string should match the given integer.




puts stringy(6) == '101010'


puts stringy(9) == '101010101'


puts stringy(4) == '1010'


puts stringy(7) == '1010101'




The tests above should print true.



Performing a task a certain number of times should be fairly straightforward at this point. We use #times to iterate based on the number indicated by size. For each iteration, we use the index block parameter in a conditional to determin...

Performing a task a certain number of times should be fairly straightforward at this point. We use #times to iterate based on the number indicated by size. For each iteration, we use the index block parameter in a conditional to determine if the current number is even or odd. Since #times starts counting from 0, we know that the first number will be even. Knowing this, we can write our conditional to return 1 if index is even and 0 if index is odd.




We assign that value to a variable and, on the next line, we add it to an array, numbers. After #times has finished iterating, we're left with an array filled with 1s and 0s in the correct order. Now, all we have to do is invoke numbers.join to return the desired output.




Modify stringy so it takes an optional argument that defaults to 1. If the method is called with this argument set to 0, the method should return a String of alternating 0s and 1s, but starting with 0 instead of 1.

Write a method that takes one argument, an array containing integers, and returns the average of all numbers in the array. The array will never be empty and the numbers will always be positive integers.Examples:




puts average([1, 5, 87, 45, 8, 8]) == 25


puts average([9, 47, 23, 95, 16, 52]) == 40






The tests above should print true.



Two things need to be done to find the average. First, add every number together. Second, divide the sum by the number of elements. We accomplish the first part by using Enumerable#reduce(also known as #inject), which combines all elements ...

Two things need to be done to find the average. First, add every number together. Second, divide the sum by the number of elements. We accomplish the first part by using Enumerable#reduce(also known as #inject), which combines all elements of the given array by applying a binary operation. This operation is specified by a block or symbol. We used a block in our solution, but we could have just as easily used a symbol, like this:




numbers.reduce(:+)




Once we have the sum, all that's left is to divide it by the number of elements. To do that, we use #count to count the number of elements in numbers. Then, we divide sum by the number of elements and return the quotient.

Write a method that takes one argument, a positive integer, and returns the sum of its digits.



puts sum(23) == 5


puts sum(496) == 19


puts sum(123_456_789) == 45




The tests above should print true.



This exercise proves to be tricky in a couple ways. First, if you tried to split the number while it was an integer you probably got an error. The key here is to convert it to a string, then split it, like this:



  23.to_s.chars # => ["2...

This exercise proves to be tricky in a couple ways. First, if you tried to split the number while it was an integer you probably got an error. The key here is to convert it to a string, then split it, like this:




23.to_s.chars # => ["2", "3"]




If you did the last exercise, you may think of using #reduce to sum the numbers in the array. If you tried this, however, you probably got unexpected results. #reduce worked, but instead of adding integers, it was adding strings, which isn't what you want. Instead, the array of strings needs to be converted to an array of integers. We can do this using #map and Ruby's shorthand syntax:




["2", "3"].map(&:to_i) # => [2, 3]




If that looks confusing, just remember that it's the same as this:




["2", "3"].map { |element| element.to_i } # => [2, 3]




It's possible to invoke all of these methods in one statement due to the return values of each method. All four of the methods used in the solution return the object we need to continue chaining methods. The following code shows the return value of each method:




23.to_s # => "23" .chars # => ["2", "3"] .map(&:to_i) # => [2, 3] .reduce(:+) # => 5

Write a method that takes two arguments, a positive integer and a boolean, and calculates the bonus for a given salary. If the boolean is true, the bonus should be half of the salary. If the boolean is false, the bonus should be 0.




puts calculate_bonus(2800, true) == 1400


puts calculate_bonus(1000, false) == 0


puts calculate_bonus(50000, true) == 25000



The solution to this exercise takes advantage of the ternary operator. We're able to use bonus as the condition because it's a boolean, which means its value will only be true or false. If it's true, then we divide salary by 2 and r...

The solution to this exercise takes advantage of the ternary operator. We're able to use bonus as the condition because it's a boolean, which means its value will only be true or false. If it's true, then we divide salary by 2 and return the quotient. If it's false, then we return 0.