Jim's
Tutorials

Fall 2018
course
site

Rails Week 4

.each loops with ruby and ternary expressions

Practiced mapping through information and altering it with .each/.each do, and read more about different ways to express these things maybe using shorter syntax with this ternary expression documentation

numbers = [1,2,3,4,5]


doubled_numbers = []

numbers.each do |number|
    doubled_numbers << number * 2
end


doubled_numbers.each do |number|
    puts number
end

-----

numbers.each do |number|
    puts number
end

---

see above for .each version

numbers = [1,2,3,4,5]
current_index = 0
max_index = numbers.length - 1

while current_index <= max_index
    puts numbers[current_index]
    current_index += 1
end

---

Checked out Ternary expressions and different ways to write these .each loops, like this:


["bridget", "barney", "sam", "ella"].each {|name| puts (name.index('b')== 0)? "#{name} starts with b" : ""}

["bridget", "barney", "sam", "ella"].each do |name|
    if name.index('b') == 0
        puts "#{name} starts with 'b'"
    end
end



names_to_greet = ['sally', 'sam', 'suzi']
names_to_greet.each { |name| puts "Hi #{name}"}

..Kept learning about different ways to do the same thing (the shorter version is better in this case)


instructors.each{|instructor|puts "hi #{instructor}"}

#can do the above also

instructors = ['dan', 'dt', 'jarvis']

instructors.each do |instructor|
    puts "hi #{instructor}"
end

# two different ways to do it- above is better

index = 0
while index < instructors.size
    puts "hi #{instructors[index]}"
    index += 1

end

any time theres a method that takes a block, its going to be pretty prescriptive in terms of the number of arguments that get passed to the pipes.



instructors = ['dan', 'dt', 'jarvis']

not_d_instructors = instructors.reject do |instructor|
     instructor[0] == "d"
end
puts not_d_instructors.inspect


instructors = ['dan', 'dt', 'jarvis']

d_instructors = instructors.select do |instructor|
     instructor[0] == "d"
end
puts d_instructors.inspect

instructors = ['dan', 'dt', 'jarvis']

d_instructors = instructors.find_all do |instructor|
     instructor[0] == "d"
end
puts d_instructors


Did similar exercises with numbers...


numbers = [2,3,4,5,3,2]

doubled_array = []

numbers.each do |number|
doubled_array << number * 2
end

puts doubled_array.inspect

Learned .map

Used the map operation to do the same thing I could do with an each block

numbers = [2,3,4,5,3,2]


doubled_array = numbers.map do |num|
    num * 2
end
puts doubled_array.inspect

and

instructors = ['dan', 'dt', 'jarvis']
greeting = instructors.map do |instructors|
    "Hi #{instructors}"
end

puts greeting.inspect

the .inject method

numbers = [2,3,4,6,3,4,2,4]
numbers.sort!

sum = numbers.inject(0) do |sum, num|
    sum += num
end
puts sum

Finally figured out the shopping cart

It's been kind of hard for me to figure out how I'm placing things in arrays and referencing them to get specific information. I finally figured out the shopping cart problem:

require 'pry'
possible_items = ['old paperback', 'potato', 'red onion', 'dried lemon', 'medicinal herbs', 'saffron']

puts "here is a list of items you can buy"

possible_items.each do |item|
    puts "#{item}"
end



pick = " "
shopping_cart = []
dont_have = []


while true
puts "what do you want to buy"
pick = gets.chomp

if pick == 'finished'
    break
elsif possible_items.include?(pick)
    shopping_cart << pick
else
    puts "sorry don't have it"
    dont_have << pick

end
end

puts "here is a list of items in your cart"
shopping_cart.each do |item|
    puts "#{item}"

end

puts "btw we noticed you put these items in there, we'll let you know if we have them"
    dont_have.each do |item|
        puts "#{item}"

end

And the output:

rrays git:(master) ✗ ruby cart.rb
here is a list of items you can buy
old paperback
potato
red onion
dried lemon
medicinal herbs
saffron
what do you want to buy
potato
what do you want to buy
saffron
what do you want to buy
happy
sorry don't have it
what do you want to buy
finished
here is a list of items in your cart
potato
saffron
btw we noticed you put these items in there, we'll let you know if we have them
happy
➜  arrays git:(master) ✗

Made a shopping cart that adds up prices for more practice. This one went easier:

prices = []

while true
    puts "whats the price of thing"
    price = gets.chomp.to_f
    prices << price

    puts "anything else? y/n"
    confirmation = gets.chomp
    if confirmation.downcase == 'n'
        break
end
end

total = 0
prices.each do |price|
    total = total + price
end

puts "your total is #{total}"

and the output:

arrays git:(master) ✗ ruby cartprices.rb
whats the price of thing
4.50
anything else? y/n
y
whats the price of thing
2.40
anything else? y/n
n
your total is 6.9

ohmygod what did I do

[1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7]
[1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

...and so on appeared with this code:

my_numbers = []


counter = 0
while counter < 100
    added_counter = counter +=1
    my_numbers << added_counter

puts my_numbers.inspect
end

FIZZBUZZ

..SO I did this on my own, but actually could not figure out how to get the "fizzbuzz" part, just the fizz and the buzz. Turns out I had to change the order so "fizzbuzz" modulos came first. I read the following documentation to try and get that last part of it- didn't actually end up using it but was interesting.

my_numbers = []

counter = 0
while counter < 100
added_counter = counter +=1
my_numbers << added_counter

end
my_numbers = my_numbers.map do |number|
    if
        (number % 5 == 0) && (number % 3 == 0)
        'Fizzbuzz'
    elsif
        number % 5 == 0
        'Buzz'
    elsif
        number % 3 == 0
        'Fizz'
    else
        number
    end
end

puts my_numbers

Getting more advanced

I practiced taking a dataset and converting it into a format that would allow me to explore it using readfile in ruby. I figured this was a good think to know how to do. followed this documentation to figure it out. Ran into some trouble trimming the "\n" off the end of everything but followed forums like this about output editing and eventually figured it out. This app is supposed to take a bunch of train numbers and times and spit out the ideal departing time for someone inquiring as to when they should leave.

in one file I had:

trains = []

File.readlines('./test.txt').each { |line| trains << line.split(",") }

trains.each do |t|
  t.each do |w|
    w.tr!("\n", '')
  end
end

puts "what time are you leaving? "
leaving = gets.chomp.to_f

if leaving <= 2
    puts "ok take #{trains[0][0]} leaving at #{trains[0][1]}"
elsif leaving <= 5
    puts "ok take #{} leaving at #{}"
elsif leaving <= 7#{}
    puts "take #{} leaving at #{}"
elsif leaving <= 8.5
    puts "take #{} leaving at #{}"
elsif leaving <= 9
    puts "take #{} leaving at #{}"
elsif leaving <=10
    puts "take #{} leaving at #{}"
elsif leaving <= 11.5
    puts "take #{} leaving at #{}"
end

In another file called "test" I put the data in the origional format they gave to me. I figured it was good practice working with whatever datasets someone might choose to vomit up to me in the future:

Train 1, 2
Train 2, 5
Train 3, 7.5
Train 4, 8.5
Train 5, 9
Train 6, 10
Train 7, 11.5
Train 8, 13.5
Train 9, 14.5
Train 10, 17
Train 11, 18
Train 12, 19
Train 13, 24

and the output ends up looking like this:

ruby next_train.rb
what time are you leaving?
1.10
ok take Train 1 leaving at  2

..So this was a success.

Moving on- symbols and Hashes

Next I skimmed the sections about symbols and hashes- practiced making a few of my own and looking at how symbols are immutable (I knew this from python but a good refresher). I made my own hash also:

pry
[1] pry(main)> 'a_string".object_id
[1] pry(main)* exit
➜  next-train git:(master) ✗ pry
[1] pry(main)> "a_string".object_id
=> 70214797541240
[2] pry(main)> :a_symbol.object_id
=> 2088668
[3] pry(main)> 'a_string'.object_id
=> 70214797343820
[4] pry(main)> 'a_string'.object_id
=> 70214797238760
[5] pry(main)> :a_symbol.object_id
=> 2088668
[6] pry(main)>
[7] pry(main)> acronym = {}
=> {}                  ^
[9] pry(main)> acronym["leslie"] ="really stupid"
=> "really stupid"
[10] pry(main)> acronym["harry"] = "really smart"
=> "really smart"
[11] pry(main)> acronym["paula"] = "kind of stupid"
from (pry):10:in `__pry__'
[12] pry(main)> acronym["paula"] = "kind of stupid"
=> "kind of stupid"
[13] pry(main)> acronym
=> {"leslie"=>"really stupid", "harry"=>"really smart", "paula"=>"kind of stupid"}
[14] pry(main)> exit

Called more methods on hashes for practice:


[14] pry(main)> acronym.empty? == false
=> true
[15] pry(main)> acronym.empty? == false
=> true
[16] pry(main)> acronym.keys
=> ["leslie", "paula"]
[17] pry(main)> acronym.values
=> ["stupid", "really smart"]
[18] pry(main)> acronym.invert
=> {"stupid"=>"leslie", "really smart"=>"paula"}
[19] pry(main)> acronym.has_key?("leslie")
=> true
[20] pry(main)> acronym.has_value?("leslie")
=> false
[21] pry(main)> acronym.has_value?("really stupid")
=> false
[22] pry(main)> acronym
=> {"leslie"=>"stupid", "paula"=>"really smart"}
[23] pry(main)> acronym.has_value?("stupid")
=> true

Then played around with more hashes and accessing that information:

moods = {
    "leslie" => "happy",
    "paula" => "sad",
    "karim" => "exillerated",
    "chris" => "angry"
}


moods.each do |key, value|
    puts "#{key} feels #{value}"
end

output:

ruby hash.rb
leslie feels happy
paula feels sad
karim feels exillerated
chris feels angry

Objects!!

Finally I got past all this array and hash crap and get to make some objects. I read documentation about initializing things and classes and how those all interplay, made a mock Person object just to get a feel for the syntax. I made some methods for my class (for my object) that describe the objects's behavior and initialized it using the @ which allows data to be passed though these "instance methods".

class Person
def initialize(name, age, mood)
    @name = name
    @age = age
    @mood = mood
end

def naptime_behavior
    "#{@name} is acting #{@mood} for naptime and that's because they are #{@age} years old"
end

def sleep_attempt
    if @age > 3
        "#{@name} refuses to sleep!"
    elsif @age <3
        "#{@name} is going to bed perfectly"
    end
end
person = Person.new("michelle", 1, "happy")
person = Person.new("chris", 4, "sad")

puts person.naptime_behavior
puts person.sleep_attempt

end

and the output:

objects git:(master) ✗ ruby practice_objects.rb
michelle is acting sad for naptime and that's because they are 1 years old
michelle is going to bed perfectly
➜  objects git:(master) ✗ ruby practice_objects.rb
chris is acting sad for naptime and that's because they are 4 years old
chris refuses to sleep!

Made a rectangle and took a look in Pry to see what was happening as I initialized a new instance of it, passing different arguments through my new rectangle:

require 'pry'


class Rectangle
    def initialize(length, width)
    @length = length
    @width = width
end
end

my_rectangle = Rectangle.new(3, 9)

binding.pry

output:

From: /Users/lesliewilson/marlboro_rails/objects/practice_objects.rb @ line 16 :

    11: end
    12: end
    13:
    14: my_rectangle = Rectangle.new(3, 9)
    15:
 => 16: binding.pry
    17:
    18:
    19: # class Person
    20: # def initialize(name, age, mood)
    21: #     @name = name

[1] pry(main)> Rectangle
=> Rectangle
[2] pry(main)> my_rectangle
=> #<Rectangle:0x007fd3a4955e00 @length=3, @width=9>

Another object:


class Book
    def initialize (title, author, category)
        @title = title
        @author = author
        @category = category

end



def summary
    "#{@title} by #{@author} genre #{@category}"
end
end


book = Book.new('user stories applied', 'mike cohn', 'technical')
puts book.summary


other_book = Book.new('pragmatic thinking', 'andy hunt','technical')

puts other_book.summary

And another, that accounts for missing values:


class Person
    def initialize(name, middle_name= nil, last_name = nil)
        if last_name.nil? & middle_name.nil?
            full_name = name.split
            @first_name = full_name[0]
            @middle_name = full_name[1]
            @last_name = full_name[2]
        else
        @first_name = name
        @middle_name = middle_name
        @last_name = last_name
    end

    def summary
        "Hi #{@first_name} #{@middle_name} #{@last_name}"
    end
end
end

    person = Person.new('john','lois', 'smith')
    puts person.summary

    other_person = Person.new('maggie ann rosenthol')
    puts other_person.summary