Last active
December 8, 2015 18:54
-
-
Save roschaefer/9c0394eb329c5a5b9046 to your computer and use it in GitHub Desktop.
Happy funny coding example - 2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Programming exercise 5.1: Assignment of Variables | |
# AKA: Give names to objects | |
###################################################################### | |
# Tutorial: http://ruby-for-beginners.rubymonstas.org/variables.html # | |
###################################################################### | |
# we can assign a variable with the equal sign = | |
a = "I am a String, and I am assigned to the variable 'a'" | |
# the right side gets 'assigned' to the variable on the left | |
b = "I am another String, and I am assigned to the variable 'b'" | |
# a variable is just an identifier, ie. a name | |
# variables are like a post-it to remember things | |
puts "We can recall a variable by it's name" | |
puts "So for example, if we want to show the string that we gave the name 'a'" | |
puts # TODO: What do we have to write after 'puts' if we want to show the variable 'a'??? | |
puts "Likewise, we can show the string associated with the variable 'b'" | |
puts # TODO: What do we have to type in here??? |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Programming exercise 5.2: Numbers and Strings | |
############################################################################################# | |
# Tutorial Numbers: http://ruby-for-beginners.rubymonstas.org/built_in_classes/numbers.html # | |
# Tutorial Strings: http://ruby-for-beginners.rubymonstas.org/built_in_classes/strings.html # | |
############################################################################################# | |
# In ruby, numbers are objects like everything else | |
puts "Is '5' an object?" | |
puts 5.is_a?(Object) | |
puts # ------------ print empty line ------------- | |
# Like any other object, numbers have methods | |
puts "Is 5.zero?" | |
puts 5.zero? | |
puts "Is 0.zero?" | |
puts 0.zero? | |
puts # ------------ print empty line ------------- | |
# So we can add two numbers and remember the result with the variable 'expression1' | |
expression1 = 2 + 5 | |
puts "The result of the expression 2 + 5 is:" | |
puts expression1 | |
# But if we add two numbers in double quotes | |
expression2 = "2" + "5" | |
# Oh, and by the way, we can write the literal quotation mark inside a string | |
# with a so called 'escape character' the backslash \ so the quotation marks | |
# don't terminate the string | |
puts "The result of the expression \"2\" + \"5\" is:" | |
puts expression2 | |
# TODO: So as you have seen in your command line, the result is '25' | |
# TODO: Can you explain why? | |
puts "Why?" | |
puts # ------------ print empty line ------------- | |
# Does this help? | |
puts "If we call \"5\".class, we get" | |
puts "5".class | |
# Does this help? | |
puts "If we call 5.class, we get" | |
puts 5.class | |
puts # ------------ print empty line ------------- | |
# TODO: We want to output a quote of Sepp Herberger here | |
puts "Attention: We will get an error message now:" | |
puts "\"No implicit conversion of Fixnum into String (TypeError)\" " | |
puts # ------------ print empty line ------------- | |
puts "Sepp Herberger: \"Das Spiel dauert " + 90 + " Minuten.\"" | |
# TODO: How can you fix that?? |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Programming exercise 5.3: Booleans and Nil | |
############################################################################################ | |
# Tutorial: http://ruby-for-beginners.rubymonstas.org/built_in_classes/true_false_nil.html # | |
############################################################################################ | |
puts # ------------ print empty line ------------- | |
# Some methods return a so called boolean value, e.g. | |
puts "Asking 5.is_a?(Object) returns the value 'true' because the number 5 is an Object" | |
puts 5.is_a?(Object) | |
puts "But the number 5 is not a String, so asking 5.is_a?(String) returns" | |
puts 5.is_a?(String) | |
puts "But if you ask me, this String, right here:" | |
puts "But if you ask me, this String, right here:".is_a?(String) | |
# Both 'true' and 'false' are protected keywords in ruby, so you can't use them as a variable name | |
# This will lead to an error | |
# true = "Something" | |
puts # ------------ print empty line ------------- | |
# There is another special value 'nil' which represents just nothing ;) | |
# Sometimes a method returns nil, e.g. 'index' gives you the first position of a character | |
puts "The first occurrence of the character 'e' in 'Auslegeware' is at position" | |
puts "Auslegeware".index("e") | |
puts "Of course we start counting at 0, like this: 0,1,2,3,4... " | |
# But what happens if we search for a character which is not in the String? | |
puts "There is no character 'Z' in 'Auslegeware' so 'Auslegeware'.index('Z') will give us" | |
p "Auslegeware".index("Z") | |
puts # ------------ print empty line ------------- | |
puts # ------------ print empty line ------------- | |
# NOTE:If you are confused about the usage of 'p' and 'puts' you can read about it in our tutorial | |
# NOTE: http://ruby-for-beginners.rubymonstas.org/writing_methods/printing.html | |
puts "By the way, I've used the method 'p' to print \"Auslegeware\".index(\"Z\")" | |
puts "It's because if you 'puts nil' then you see:" | |
puts nil | |
puts # ------------ print empty line ------------- | |
puts "An empty line! Does that make sense? You simply print nothing! :)" | |
puts "But if you use 'p nil' then you see" | |
p nil | |
puts # ------------ print empty line ------------- | |
puts "The literal description of the value 'nil' which a String consisting of the characters n-i-l" | |
puts "Calling 'p something' is equivalent to 'puts something.inspect'" | |
puts nil.inspect | |
puts "See?" | |
puts # ------------ print empty line ------------- | |
puts "One more thing: In ruby (almost) everything is an object, including 'nil', 'true' and 'false'" | |
puts "Therefore we can call methods on these objects, e.g. \"nil.nil?\"" | |
puts nil.nil? | |
puts "Isn't that cool? We can ask the pure void: \"Are you nil?\" and it will tell us: \"Yes.\"" | |
puts # ------------ print empty line ------------- | |
puts "This is just one reason why ruby is awesome" | |
puts "In other programming languages you have to *compare* your object with nil" | |
some_object = nil | |
puts some_object == nil # NOTE: The double equal sign here | |
# TODO: Write a philosophical essay about the meaning of the void (nothingness) in programming languages | |
# TODO: Express the meaning of truth and untruth from a development perspective in a public debate |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Programming exercise 5.4: 'puts' and 'gets' | |
########################################################################################################### | |
# StackOverflow: http://stackoverflow.com/questions/5018633/what-is-the-difference-between-print-and-puts # | |
# StackOverflow: http://stackoverflow.com/questions/6556280/read-input-from-console-in-ruby # | |
# Ruby-Doc Kernel#puts: http://ruby-doc.org/core-2.2.3/Kernel.html # method-i-puts # | |
# Ruby-Doc Kernel#gets: http://ruby-doc.org/core-2.2.3/Kernel.html # method-i-gets # | |
# Ruby-Doc String#strip: http://ruby-doc.org/core-2.2.0/String.html#method-i-strip # | |
########################################################################################################### | |
# Although not covered in depth by our tutorial I want to talk a little about the methods | |
# that print something on the screen and also how to get user input from the screen | |
# The methods 'puts' prints a string on the screen | |
puts "So for example, this string gets printed on the screen" | |
# There are several other methods how to print something on the screen, e.g. | |
print "The method 'print' prints " | |
print "without a line break " | |
print "at the end. " | |
puts # ------------ print empty line ------------- | |
print "Can you see the difference to 'puts'? " | |
print "Of course we can print a newline character like so: \n" | |
print "\n" # ------------ print another empty line ------------- | |
# The methods 'gets' waits for user input and returns another string | |
# However, 'gets' also captures the line break at the end | |
puts "Dear user, please enter some text and hit return ;)" | |
user_input = gets | |
puts "Here comes the user input: " + user_input + " but this is on a new line .." | |
# So we have to call a method on the string to get rid of the new line | |
# We can use either 'strip' or 'chomp', in our example the difference doesn't matter | |
puts "Here comes the user input: " + user_input.strip + " without a new line .." | |
# We can also call 'strip' on the return value of 'gets' directly | |
puts "Please input something else:" | |
new_user_input = gets.strip | |
puts "The new user input " + new_user_input + " has no line break at the end - got that? :)" | |
puts "Press enter to see how all the following words are separated by a line break" | |
gets | |
# Whitespaces are invisible characters | |
# So to make them visible in the source code we use the backslash together with a character | |
# E.g. this \n means a line break in the string | |
puts "These\nwords\nare\nall\non\na\nnew\nline" | |
# TODO: here are some strings with trailing newlines | |
string = "The quick brown fox \n" | |
string2 = "Jumps over the lazy dog" | |
# TODO: Put these strings together without a newline! | |
puts "Ready to see the output of your exercise?" | |
gets | |
puts string + string2 | |
# TODO: What do you have to call on the first string to remove the line break at the end? |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Programming exercise 5.5: Arrays | |
####################################################################################### | |
# Tutorial: http://ruby-for-beginners.rubymonstas.org/built_in_classes/arrays.html # | |
####################################################################################### | |
# Arrays or Lists are special objects to group many other objects into one | |
# Arrays are written with square brackets | |
empty_array = [] | |
puts "This is how an empty array looks like" | |
p empty_array | |
puts # ------------ print empty line ------------- | |
# Values in arrays are separated with commas | |
puts "Array with some elements" | |
array = [1, "two", 3.0, nil, true] | |
p array | |
puts # ------------ print empty line ------------- | |
# You can access an element at a certain position like so | |
puts "The first element is" | |
p array[0] # We always start counting with 0 | |
puts # ------------ print empty line ------------- | |
# You can overwrite an item of an array | |
puts "The array before we change it" | |
p array | |
array[0] = "one" # We always start counting with 0 | |
puts "The array after our change" | |
p array | |
puts # ------------ print empty line ------------- | |
# And finally we can add new items to the array | |
puts "The array before we add something" | |
p array | |
array << "a new item" | |
puts "The array after we added something" | |
p array | |
puts # ------------ print empty line ------------- | |
# Iterating over an array: | |
# If you want to do something with each element, you can call 'each' on the array | |
# This is a special method that expects a so called 'block' | |
# The block is the code between 'do' and 'end' | |
# A block can take some arguments, written between the pipe symbols |arg1, arg2, ...| | |
# In this example, 'each' expects a block with just one argument |item| | |
# This way, the block will be applied on every item in the list | |
puts "Now we're calling 'p' on every item in our array" | |
array.each do |item| | |
p item # here, item is a local variable which represents an item in the list | |
end | |
# TODO: Here is an array with some numbers | |
numbers = [1,2,3,5,7,11,13] | |
# TODO: Multiply every number in the list with 2 and show it on the screen | |
# TODO: ----------------- your code here ------------------------- | |
# TODO: Now instead of printing the elements, create an empty array | |
# TODO: And then multiply every item of 'numbers' by 2 and add it to the new array | |
# TODO: Print the new array | |
# TODO: ----------------- your code here ------------------------- | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Programming exercise 5.6: Writing methods | |
############################################################################ | |
# Tutorial: http://ruby-for-beginners.rubymonstas.org/writing_methods.html # | |
############################################################################ | |
puts # ------------ print empty line ------------- | |
# Methods are like a reusable piece of code | |
# They consist of four things: | |
# 1. A name | |
# 2. Some arguments, representing the input | |
# 3. A block of code | |
# 4. A return value, representing the output | |
def print_something | |
puts "Aloha!" | |
end | |
# Everything between 'def' and 'end' belongs to the method definition | |
# Just definining the method doesn't execute the code | |
# We have to call the method in order to run it | |
puts "If we call the method 'print_something' we see:" | |
print_something | |
puts # ------------ print empty line ------------- | |
# Every method has a return value, which we can use | |
def return_a_string | |
# Usually, the return value is the value of the last evaluated line | |
"I am the return value" | |
end | |
puts "So this is the return value of the method 'return_a_string'" | |
puts return_a_string | |
puts # ------------ print empty line ------------- | |
# Can you see that we have to call 'puts' in order to show the value on the screen? | |
# Here we care about the return value of the method | |
# If we just call the method without passing it to 'puts' we don't see anything | |
return_a_string # this doesn't print anything | |
# Here you can see an explicit 'return' statement in the method | |
# Calling 'return' immediately leaves the method and returns the expression right next to it | |
def method_with_explicit_return_statement | |
return "I am the string returned by the return statement" | |
"I won't get returned, because you leave the method with 'return'" | |
end | |
puts "Here is the explicit return value:" | |
puts method_with_explicit_return_statement | |
puts # ------------ print empty line ------------- | |
# Methods can have arguments (input) | |
def say_hello_to(something) | |
puts "Hello " + something | |
# By the way: 'puts' returns nil | |
# It is the last line of the method so we return nil here | |
end | |
say_hello_to("YOU!") | |
puts # ------------ print empty line ------------- | |
# Methods can have arguments | |
def introduce_two_people(person1, person2) | |
# Arguments are like local variables | |
# So we can think that 'person1' and 'person2' are just names | |
# for objects that we pass to the method | |
puts "Hello " + person1 + " this is " + person2 + "." | |
puts "Hello " + person2 + " this is " + person1 + "." | |
end | |
introduce_two_people("Wisal", "Annika") | |
# TODO: define a method that adds two numbers | |
def add(number1, number2) | |
# TODO: what comes in here? | |
# Remember: you can add numbers with a plus sign, e.g. 1 + 2 | |
end | |
# TODO: this should print 3 on the screen | |
puts "If we call the method add(1,2) we see:" | |
puts add(1,2) | |
# TODO: What happens if you call the method add without arguments? | |
# TODO: Do you understand why? | |
# TODO: Define a method with a name that you choose on your own ;) | |
# TODO: The method should expect some arguments and does something interesting |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Programming exercise 5.7: Writing Classes - part 1 | |
############################################################################ | |
# Tutorial: http://ruby-for-beginners.rubymonstas.org/writing_classes.html # | |
############################################################################ | |
class Person | |
def initialize(name) | |
# This is a so called 'instance variable' | |
# Instance variables belong to an object and in contrast to local variables | |
# they don't disappear after we leave the method | |
# but are saved as long as the object lives | |
@name = name | |
end | |
def name | |
@name | |
end | |
def rename(name) | |
# TODO: what do we have to write here | |
end | |
end | |
# We will learn in this small example that objects have state | |
# Every instance of a class has its own state | |
person = Person.new "Alice" | |
# So the person has got the name "Alice" initially | |
# The method 'new' calls internally the so called constructor 'initialize' | |
# Read about it here: http://ruby-doc.org/core-1.9.3/Class.html#method-i-new | |
# The 'initialize' method is where we set the initial name | |
puts "The person is called #{person.name}" | |
# But why doesn't this change anything?? | |
person.rename "Bob" | |
puts "The new name for the person is #{person.name}" | |
# TODO: How can we change the code above to output the new name? | |
person.rename "Carl" | |
puts "Again, the new name for the person is #{person.name}" | |
person2 = Person.new "Carl" | |
# This second person is another instance of class 'Person' | |
# Although it may have the same name as our first person, it is another person object | |
puts "Do the two persons have the same name?" | |
puts person.name == person2.name | |
puts "Are the two persons the same object?" | |
puts person.equal?(person2) | |
puts "Although two objects may have the same values, they are still different!" | |
# Does that make sense? | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Programming exercise 5.8: Writing Classes - part 2 | |
############################################################################ | |
# Tutorial: http://ruby-for-beginners.rubymonstas.org/objects.html # | |
# Tutorial: http://ruby-for-beginners.rubymonstas.org/writing_classes.html # | |
############################################################################ | |
class Sheep | |
def initialize | |
@hungry = 3 | |
@tired = true | |
end | |
def wake_up | |
@tired = false | |
puts "Yaaaawwn. Good morning! ;)" | |
end | |
def sleeping? | |
@tired | |
end | |
def hungry? | |
@hungry > 0 | |
end | |
def eat_grass | |
if sleeping? | |
puts "I'm still asleep! You have to wake me up!" | |
else | |
if hungry? | |
puts "Mmmh, yummy grass!" | |
@hungry = @hungry - 1 | |
end | |
if hungry? | |
puts "I'm still hungry! I want to eat more grass." | |
else | |
puts "Now I'm full!" | |
end | |
end | |
end | |
end | |
# This is just another exercise on object oriented programming | |
# Here we have to call certain methods on the object to reach our goal | |
# You don't have to change the class' definition | |
# Okay, so we are creating a new instance of class sheep here | |
sheep = Sheep.new | |
# TODO: Feed the sheep until it's full! | |
# TODO: If we call sheep.eat_grass, the sheep will tell us it's still sleeping | |
# TODO: What method do we have to call on the sheep first?? | |
sheep.eat_grass | |
sheep.eat_grass | |
# TODO: So, which methods, in which order and how often do we have to call them? | |
# TODO: Can you imagine how the objects state changes when you call certain methods? | |
# TODO: Call 'p sheep' between your steps | |
p sheep | |
# TODO: So you can see how the instance variables of the sheep change |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Programming exercise 5.9: Object scope | |
################################################################################# | |
# Tutorial: http://ruby-for-beginners.rubymonstas.org/writing_classes/self.html # | |
################################################################################# | |
class Person | |
def initialize(name) | |
@name = name | |
end | |
def name | |
@name | |
end | |
def greet(other_person) | |
#This local variable shadows the method 'name' | |
name = "Not my name" | |
# TODO: We have a name clash betweeen a local variable and a method name | |
# TODO: How can we be specific? | |
# TODO :How can we call a method on the current object? | |
puts "Hi " + other_person.name + "! My name is " + name + "." | |
end | |
end | |
person = Person.new("Alice") | |
friend = Person.new("Bob") | |
person.greet(friend) | |
# TODO: What do we have to change in class Person above? | |
# TODO: We want to let Alice tell her actual name to her friend Bob! | |
# TODO And vice versa | |
friend.greet(person) | |
# NOTE: The 'lookup' of identifiers is sometimes tricky | |
# NOTE: An identifier could be a local variable or a method | |
# NOTE: In the above example it makes the code even more readable to use 'self' | |
# NOTE: 'self' is the keyword that always refers to the current object | |
# NOTE: We call that an 'explicit receiver', sth. on which we call a method (sth.method) | |
# NOTE: Keywords can never be used as variable names | |
# NOTE: Do you want to try it out? | |
# TODO: Uncomment the following lines of code individually and see what happens | |
#self = "Self" | |
#true = false | |
#nil = 0 | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Programming exercise 5.10: Blocks | |
################################################################### | |
# Tutorial: http://ruby-for-beginners.rubymonstas.org/blocks.html # | |
################################################################### | |
# Our Tutorial says: "Blocks are one of the things programmers absolutely love about Ruby" | |
# And as a ruby developer I can conirm that! | |
# A block is like an anonymous method | |
# It has got input(arguments), some code and an output but no name - therefore we call it 'anonymous method' | |
# A block is always passed to a method call | |
# We have come across one example already: | |
5.times do |time| | |
puts "It's the #{time+1} time that we enter the block" | |
end | |
# The block is everything between do ... end | |
# The arguments that are passed to the block are between the pipes || | |
# So we have an argument |time| in this example | |
# A block is always passed to a method, which is 'times' in the last example | |
# There is an alternative syntax for blocks which is curly braces | |
3.times { puts "Hello from inside a block!" } | |
# Blocks can have return values like methods | |
# E.g. the method 'map' on an array runs the block on every item in the list and returns the resulting array | |
numbers_plus_three = [1,3,5,6,10].map {|number| number + 3 } | |
# We add 3 to every number in the list and assign the result to the variable 'numbers_plus_three' | |
p numbers_plus_three | |
puts # ------------ print empty line ------------- | |
# TODO: Show only the odd numbers on the screen! | |
# NOTE:The method 'select' selects only items from an array, on which a block evaluates to 'true' | |
# NOTE: read http://ruby-doc.org/core-2.2.3/Enumerable.html#method-i-select | |
# NOTE: 'odd?' tells you if a number is odd or not | |
# NOTE: read http://ruby-doc.org/core-1.8.7/Integer.html#method-i-odd-3F | |
puts "All the odd numbers are" | |
puts [1,2,3,4,5,6,7] # what do we have to call on the array? | |
# TODO: Show the first string that includes 'woo'! | |
# NOTE:The method 'find' is very similar to 'select' but it only returns the first item | |
# NOTE: read http://ruby-doc.org/core-2.2.3/Enumerable.html#method-i-find | |
# NOTE: The method 'include?' tells you if a String includes another String | |
# NOTE: read http://ruby-doc.org/core-2.2.0/String.html#method-i-include-3F | |
puts "The first String that includes 'woo' is" | |
puts ["Ruby is cool", "Rubies in the woods", "Ruby Monstas"] # what do we have to call on the array? | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Programming exercise 6.10: Blocks | |
##################################################################################### | |
# Tutorial: http://ruby-for-beginners.rubymonstas.org/built_in_classes/symbols.html # | |
# Tutorial: http://ruby-for-beginners.rubymonstas.org/built_in_classes/hashes.html # | |
##################################################################################### | |
# We have skipped over two very relevant basic data types in ruby: | |
# Symbols and Hashes | |
# ============= Symbols =============== | |
# Symbols are a very specific concept in ruby | |
# Their purpose is to label things | |
# A symbol is written like a word preceded by a colon: | |
:word | |
# It is somehow similar to a string but it's mere value already identifies it | |
puts "Do the two strings 'word' and 'word' have equal values?" | |
puts "word" == "word" | |
puts "Do the two symbols :word and :word have equal values?" | |
puts :word == :word | |
puts "Are the two strings 'word' and 'word' the same object?" | |
puts "word".equal?("word") | |
puts "Are the two symbols :word and :word the same object?" | |
puts :word.equal?(:word) | |
# Confused? Good! :D | |
# Don't worry. No one understands symbols at the very first time. | |
# If you are from the java world then you might find symbols similar to 'enums'. | |
# It's really hard to explain the meaning of symbols to absolute beginners | |
# 1. Best explanation: Our tutorial | |
# "Symbols are unique identifiers that are considered code, not data" | |
# 2. Second best explanation: Tags or Labels | |
# Use symbols if you want to talk about "Who?" instead of "What"? | |
# 3. Lengthy explanation including implementation details: | |
# http://stackoverflow.com/q/16621073 | |
puts # ------------ print empty line ------------- | |
# ============= Hashes =============== | |
# A 'Hash' in ruby is a set of key-value pairs - a special data structure | |
# In other languages it may have the name 'Dictionary' or 'Map' | |
# Wikipedia calls it 'associative array' | |
# Wikipedia: https://en.wikipedia.org/wiki/Associative_array | |
# A Hash is written with curly braces | |
a_hash = {"I am" => "a hash"} | |
# Here the String "I am" is the key for the String "a hash" | |
# Because a Hash is also called dictionary in programming languages like Java | |
# We can make an actual english dictionary with more than one key-value pair | |
english_dictionary = { | |
"hello" => "Hallo", | |
"goodbye" => "Auf Wiedersehen", | |
"thanks" => "Danke" | |
} | |
# Everything between '{' and '}' belongs to the hash | |
# We can add more key-value pairs to the hash like so: | |
english_dictionary["sorry"] = "Entschuldigung" | |
# And we can retrieve words from a hash like this: | |
puts "return value of 'english_dictionary[\"thanks\"] is" | |
puts english_dictionary["thanks"] | |
puts # ------------ print empty line ------------- | |
# The whole point about hashes is that you don't need to remember an element | |
# in a collection by it's position (like in a list) but you can remember the | |
# element with a so called 'key' | |
# E.g consider this example with two lists | |
english_words = ["hello", "goodbye", "thanks"] | |
german_words = ["Hallo", "Danke", "Auf Wiedersehen"] | |
# We made a little mistake here: The order of corresponding words doesn't match | |
puts "There is a mistake in the following translations" | |
english_words.each_with_index do |word, index| | |
puts "The german translation of '#{word}' is : #{german_words[index]}" | |
end | |
# TODO: change the code above, so that the right translation appears on the screen | |
# Do you see that this is a possible source for errors? | |
puts # ------------ print empty line ------------- | |
# TODO: Let's consider this example | |
sentence = "Please translate this sentence" | |
# TODO: Add more key-value pairs to the english_dictionary! | |
# TODO: At least the translations for 'Please', 'translate', 'this' and 'sentence' | |
# NOTE: If you use the infinitive for 'translate' no problem! | |
# NOTE: This is only a good showcase why translation of natural languages | |
# is a tough problem | |
# ------------ add more key-value pairs to 'english_dictionary' here ---------- | |
# We can split a string into a list of strings with 'split' | |
words_of_sentence = sentence.split(" ") | |
puts "The sentence split into words looks like this" | |
p words_of_sentence | |
# We can iterate over a list with 'collect' and return a new list | |
# NOTE: This time, the curly braces indicate a block | |
translated_words = words_of_sentence.map {|word| english_dictionary[word]} | |
puts "The list of translated words looks like this" | |
p translated_words | |
# We can combine a list of strings into one string with 'join' | |
puts "The final sentence looks like this" | |
puts translated_words.join(" ") | |
puts # ------------ print empty line ------------- | |
# Now why do we introduce symbols and hashes in one example? | |
# Because symbols are often used as keys for a hash | |
# Remember that we said, use symbols when you talk about "Who" instead of"What"? | |
hash_with_symbols = { | |
:a_symbol => "is just perfect", | |
:as_a_key => "for a value" | |
} | |
# By the way: You can store any object in a hash, not just Strings | |
hash_with_symbols[:a_number] = 42 | |
hash_with_symbols[:a_list] = ["one", 2, 3.0, :four] | |
hash_with_symbols[:another_hash] = {:foo => :bar} | |
puts "The 'hash_with_symbols' contains" | |
p hash_with_symbols | |
# TODO: create a command line form for address details | |
address_details = { | |
:name => nil, | |
:street => nil, | |
:zip_code => nil, | |
:city => nil, | |
} | |
puts "Your address please!" | |
address_details.keys.each do |key| | |
puts "Please type in your #{key.capitalize}" | |
# TODO: access the user input with 'gets' | |
# TODO: save the input the corresponding key in the 'address_details' | |
# NOTE: we iterate over all keys in this loop, so you've got the 'key' ;) | |
end | |
puts # ------------ print empty line ------------- | |
puts "Great! We will send your package to:" | |
address_details.each do |key, value| | |
puts "#{key.capitalize}: #{value}" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment