Based on the Ruby Basics Card in the developer Curriculum
Ruby is the programming language we use on the backend.
After finishing this lesson you should be able to read and write simple Ruby programs.
Gain an understanding of the following concepts:
return, implicit return in methods and blocks
Here are some tutorial to get you started with learning Ruby. You don't need to read them all. Pick some that work for you.
When you're looking for detailed information on a Ruby class or method, you can Google it or use one of these references:
Create a separate Merge Request in Gitlab for every exercise.
Write a small ruby programm
count_words.rb that accepts a filename, counts the number of words, lines and paragraphs, and outputs the result.
$ ruby count_words.rb test.txt test.txt has 123 words test.txt has 13 lines test.txt has 4 paragraphs
- Find out about
- Look up
Filein one of the references above.
- You can create random text on.
Contact class that models an address book entry.
It should offer an API like this:
contact = Contact.new(first_name: 'Anna', last_name: 'Muster', street: 'Foo Avenue 77') contact.first_name # => 'Anna' contact.last_name # => 'Muster'
Contact object should be able to store:
All fields are optional, except for
#last_name. If we try to instantiate a contact without a last name, the constructor raises an error:
Contact.new(first_name: 'Anna') # raises ArgumentError
Now build an
AddressBook class that can store a list of contacts in memory:
addresses = AddressBook.new addresses.add Contact.new(first_name: 'Frederik', last_name: 'Foo') addresses.add Contact.new(first_name: 'Berta', last_name: 'Beispiel', phone: '556677') addresses.add Contact.new(first_name: 'Anna', last_name: 'Muster', street: 'Foo Avenue 77') addresses.size # => 3
Now write a method
AddressBook#search that takes a query string and returns an array of
Contact objects that match the given word in any of their properties (name, street, city, etc.):
results = addresses.search('foo') # returns an Array of "Frederik" and "Anna" contacts results.size # => 2 results.class # => Contact results.first_name # => "Frederik" results.street # => "Foo Avenue 77"
You can convert any object to a string by calling
The matching should be.
Also when the query string contains more than one word, it returns contacts that match all of the words in any property:
results = addresses.search('77 berta') results.size # => 1 results.first_name # => "Berta"
AddressBook class so the
#add method throws a
DuplicateContact error when the user tries to add a contact that already exist. We consider two contacts to be duplicates if they have the same first and last name.
Create athat inherits from