The Random 7

No, it’s not the most recently leaked Tarantino Screenplay. I’m of course referring to a challenging conundrum my bootcamp cohort friend showed to me. The problem is a little lax on wording but I’ll try to interpret it the best I can. Simply put, the challenge says,

“Given a function rand5(), implement rand7()”

By rand5() they mean a random integer between 1 and 5, inclusive. I completed this task using ruby, so I’ll present the necessary code to complete using THEIR wording.

rand(5) won’t work because it includes ‘0’.

When I first started thinking about this problem, I was confused as to what I would need to do because it seems impossible that given an assortment of 5 possible random outcomes, one could generate a random number between 1 and 7. I started considering strange possibilities, but the answer was right under my nose. Using the .sample method on an array of arrays. See below.

rand7 = [
 [1, 2, 3, 4, 5, 6, 7],
 [1, 2, 3, 4, 5, 6, 7],
 [1, 2, 3, 4, 5, 6, 7],
 [1, 2, 3, 4, 5, 6, 7],
 [1, 2, 3, 4, 5, 6, 7]
]

100.times { puts rand7[rand((1..5))-1].sample }

By utilizing the rand5() concept to randomize an array’s index, you can just use sample to call a random 1-7.

I also wanted to do the same using the true ruby method rand(5) => rand(7), so that’s below:

rand7 = [
 [0, 1, 2, 3, 4, 5, 6],
 [0, 1, 2, 3, 4, 5, 6],
 [0, 1, 2, 3, 4, 5, 6],
 [0, 1, 2, 3, 4, 5, 6],
 [0, 1, 2, 3, 4, 5, 6]
]

100.times { puts rand7[rand(5)].sample }

I realize this way may seem easier than people have made the problem, but if I’m understanding it correctly, it doesn’t need to be that hard.

The Random 7

Rails: Passing Parameters to your page; Using user input

If you’re like me, you comprehend the gets.chomp methods as a way to gather information from your user. Rather fortunately however, the command line isn’t really available to your user and they probably wouldn’t know what to do with it if it were. We are accustomed to clicking links and the application rendering a new view with your item featured. Etsy would be quite clunky if you could never view an item you like by itself. Sorting how rails accomplishes this is a trickier topic than most tutorial basics show you, but at the same time, the only other advanced tutorials tend to be overly wordy and convoluted.

Lets pick apart a popular way of getting user defined parameters and using them accordingly. Lets say we have a run-of-the-mill eCommerce rails app.

# we have a landing route to the list of all products
# when a user inputs <domain>/home into their browser...

# config/routes.rb
get '/home' => 'products#show_all

# when the browser goes to the /home url,
 the products controller starts the show_all method.

# this gets triggered in /app/controllers/products_controller.rb
class ProductsController < ......

    def show_all
         @products = Product.all
    end

end

At this point, @products is a variable made available to us on the show_all.html.erb view. It contains all the objects of class Product and can be iterated and manipulated accordingly. But what if you want to see a particular item, say, the Product with ID #2 in the database?

# to see this Product with ID#2 the user needs to pass
 Parameters along with the get request

# this time the user is going to type into their browsers
 address bar: "<domain>/products/2"

#config/routes.rb showing previous path and NEW PATH needed:
get '/home' => 'products#show_all
get '/products/:item_number' => 'products#show_product'

# now we need a new method to make use of the route defined above
class ProductsController < ......
    def show_all
        @products = Product.all
    end

    # this is when we use params to pass the variable
 in the route (:id) to the controller 

    def show_product
       @product = Product.find_by(id: params[:item_number]) 
    end
end

Now @product is available to your view. It will be unique because you used it’s database id to look it up. This can be trickier when searching by name or other non unique attributes, but with the default :id it’s a sure fire thing. Hopefully this is just simple and basic enough to help you wrap your head around the concept and get it working. Don’t worry about feature functionality at this point. It’s important to know these mid level skill things and how they work, even if a user would never operate your app this way.

Rails: Passing Parameters to your page; Using user input

A New Way to Compare Hashes in Ruby 2.3

I must admit, this is pretty cool. Maybe not the most amazing thing you’ve ever heard of, but still, moves like this perfectly demonstrate the high functioning hive-mind of the ruby community. This new way to compare hashes was pretty sweet to me, so I wanted to share it with you.

#the old way of comparing hashes, which doesn't make sense.
{ a: 1, b: 2 }.include?({a: 1})
=> false

That evaluates to false because Hash#include can’t check for a key value pair, it can only check if the key exists.

#new to ruby 2.3
{ a: 1, b: 2 } >= { a: 1 }
=> true

{ a: 1, b: 2 } >= { a: 2 }
=> false

The hash on the top left is larger and includes the smaller hash on the right, so it evaluates to true. The one beneath is larger but doesn’t contain the key value pair on it’s right.

Have at it!

A New Way to Compare Hashes in Ruby 2.3

Topic: How [misemployed] Sarcasm Affects the Progressive Idea Incubator

We’ve all heard the routine before. It doesn’t matter where you work or in what industry. The setup is always the same and the payoff always leaves the audience wanting. I’ll reenact it for you:

Bob: “Hey there, Sandy. How are you?”

Sandy: “Oh, great how are you? What can I help you with?

Bob: “I’ve got this idea about our TPS reports that I was wondering if you could help me with. Do you have a few minutes?”

( here comes the hilarious joke )

Sandy: “NOOOOOOOOO…  no, I’m just kidding, yeah lets take a look.”

Ok, now if you think I’m overstepping here, I want to point out some key fundamentals to explain why my argument is both valid and thoughtful. This isn’t about being aggressively PC (which is for the birds) or not being able to express yourself in the work place, to be fair.

  • First and foremost – this “joke” is so tired, you’re probably coming across as completely out of touch with anything comically relevant  AT ALL. So aside from it just being sort of off-putting, it’s also not funny.
  • Bob could be very nervous about even speaking up or approaching someone with his idea and, I’m sure, doesn’t love the fact the initial reaction to his idea from a coworker, who’s goals are supposed to be inline with his own, is that of negative impulsivity.
  • If your gut reaction is to respond with a non-humorous and dilapidated relic of a conversation contribution, then you seriously need to check yourself.
  • THIS IS OF COURSE, not the case if you go about saying “NOOOOOOOO” in a completely over-the-top manner, in a way the goes so far as to humiliate yourself in order to make Bob feel more comfortable and score yourself some office interest in your “comedy” troupe that’s playing this Saturday at a rehabbed theater nearby. That type of “NOOOOOOOO” is both welcomed and cherished by all.

So how does this affect your workplace? Well, if done the wrong way, it makes that person seem like a non-funny ass-hat that *acts* like they want to participate with new ideas, but really, they don’t want to be bothered. That’s damaging for relationships and company progress. If you are constantly met with this aforementioned negative impulsiveness, frankly there may be something wrong with the climate of happiness at work. It certainly makes you think twice before approaching people with new ideas again.

Topic: How [misemployed] Sarcasm Affects the Progressive Idea Incubator

The Deck of Cards: A great intro to OOP

When I first started getting into object-oriented programming, I thought about things around the house I could model to help make more sense of what exactly OOP is. I personally feel that creating a deck of cards in ruby is what helped me get over the initial hump of wrapping my head around it.

Below, I wrote a bit of code that could be used as a base template for a deck of cards with aces high.

class Card

 attr_reader :number, :suit, :value

 def initialize(number, suit, value)
 @number = number
 @suit = suit
 @value = value
 end

end

class Deck
 
 attr_reader :deck
 
 def initialize
 @deck = [
 Card.new("2", "Hearts", 1),
 Card.new("3", "Hearts", 2),
 Card.new("4", "Hearts", 3),
 Card.new("5", "Hearts", 4),
 Card.new("6", "Hearts", 5),
 Card.new("7", "Hearts", 6),
 Card.new("8", "Hearts", 7),
 Card.new("9", "Hearts", 8),
 Card.new("10", "Hearts", 9),
 Card.new("Jack", "Hearts", 10),
 Card.new("Queen", "Hearts", 11),
 Card.new("King", "Hearts", 12),
 Card.new("Ace", "Hearts", 13),
 Card.new("2", "Spades", 1),
 Card.new("3", "Spades", 2),
 Card.new("4", "Spades", 3),
 Card.new("5", "Spades", 4),
 Card.new("6", "Spades", 5),
 Card.new("7", "Spades", 6),
 Card.new("8", "Spades", 7),
 Card.new("9", "Spades", 8),
 Card.new("10", "Spades", 9),
 Card.new("Jack", "Spades", 10),
 Card.new("Queen", "Spades", 11),
 Card.new("King", "Spades", 12),
 Card.new("Ace", "Spades", 13),
 Card.new("2", "Diamonds", 1),
 Card.new("3", "Diamonds", 2),
 Card.new("4", "Diamonds", 3),
 Card.new("5", "Diamonds", 4),
 Card.new("6", "Diamonds", 5),
 Card.new("7", "Diamonds", 6),
 Card.new("8", "Diamonds", 7),
 Card.new("9", "Diamonds", 8),
 Card.new("10", "Diamonds", 9),
 Card.new("Jack", "Diamonds", 10),
 Card.new("Queen", "Diamonds", 11),
 Card.new("King", "Diamonds", 12),
 Card.new("Ace", "Diamonds", 13),
 Card.new("2", "Clubs", 1),
 Card.new("3", "Clubs", 2),
 Card.new("4", "Clubs", 3),
 Card.new("5", "Clubs", 4),
 Card.new("6", "Clubs", 5),
 Card.new("7", "Clubs", 6),
 Card.new("8", "Clubs", 7),
 Card.new("9", "Clubs", 8),
 Card.new("10", "Clubs", 9),
 Card.new("Jack", "Clubs", 10),
 Card.new("Queen", "Clubs", 11),
 Card.new("King", "Clubs", 12),
 Card.new("Ace", "Clubs", 13)
 ]
 end

 def mix
 @deck.shuffle!
 end

 def deal
 @deck.shift
 end

 def cards_left
 @deck.length
 end

end

# using the classes:

#create the deck and assign it a variable
new_full_deck = Deck.new

#shuffle the cards
new_full_deck.mix

#deal a card
new_full_deck.deal
=> <CARD OBJECT>

A deck of cards is an object that has many objects (cards) that are very familiar to our brains, so creating a deck of other card object really helped me understand OOP.

The Deck of Cards: A great intro to OOP

Finding Prime Numbers in a Range

So this was kind of cool. I needed a way to pump out all the prime numbers in a range in order to solve problem #3 in the excellent web zone, projecteuler.net, which I can’t recommend enough. I’m still trying to figure out how to do the prime factorization so any help is appreciated in the comments. This works quite well and returns an array of primes from 1 to whatever you choose. You can of course create a gets.chomp for the lower end of the range.

# Prime numbers within a range

@prime = []

def is_prime(number)
 divisors = []
 (1..number).each { |n| divisors << n if number%n == 0 }
 if divisors.length == 2 || divisors.length == 1
 @prime << number
 end
end

puts "Find all the prime number between 1 and...?"

max_num = gets.chomp.to_i

(1..max_num).each { |n| is_prime(n) } 

p @prime
Finding Prime Numbers in a Range

The Banking Select an Account Problem

In this exercise I was asked to obtain [first_name], [last_name], and [email] for 5 people. Those people should be entered into an array of hashes and then I should be able to recall a person by giving the account number back to the program which had been randomly created into a 10 digit number.

The 5.times loop was the choice in order to capture info, but when it came time to generate a random number that always contained 10 digits (leading zeros if necessary) I had to get a little fancier. Ruby doesn’t have a built in way of formatting this with a simple method. One way I saw was to use right justification and ply in leading a number of zeros based on length of the number string. I used a different approach with center justification.

# random 10 digit number
acct_number = rand(9999999999).to_s.center(10, rand(9).to_s).to_i

The next fun problem was to retrieve the info. I used the Enumerable#select method like so:

# returns a person array with a single person's hash inside
person = people.select { |person| person["acct_number"] == account_lookup }

And here’s the complete code:

people = []
5.times {
 puts "Enter the person's first name:"
 first_name = gets.chomp
 puts "Enter the person's last name:"
 last_name = gets.chomp
 puts "Enter the person's email:"
 email = gets.chomp
 until email.include?("@") && email[-4..-1] == ".com" && email.include?(" ") == false
 puts "#{email} is not a valid email address. Enter a valid email address:"
 email = gets.chomp
 end
 acct_number = rand(9999999999).to_s.center(10, rand(9).to_s).to_i
 people << { "first_name" => first_name, "last_name" => last_name, "email" => email, "acct_number" => acct_number }
 puts "USER# #{acct_number} ADDED."
}

people.each { |person|
 puts "FIRST NAME: #{person["first_name"]}"
 puts "LAST NAME: #{person["last_name"]}"
 puts "EMAIL: #{person["email"]}"
 puts "ACCOUNT NUMBER: #{person["acct_number"]}"
}

puts "Enter an account number to look up:"
account_lookup = gets.chomp.to_i

person = people.select { |person| person["acct_number"] == account_lookup }

puts "FIRST NAME: #{person[0]["first_name"]}"
puts "LAST NAME: #{person[0]["last_name"]}"
puts "EMAIL: #{person[0]["email"]}"
puts "ACCOUNT NUMBER: #{person[0]["acct_number"]}"
The Banking Select an Account Problem

Setting Sail

4078379_orig

Yesterday my journey began. It had been a long time coming, but yesterday all the pieces fell into place and my path to becoming a fancy web developer really picked up anchor and slowly set adrift.

Enough sailing metaphors.

This is my first post about my code-schooling. My aim is to make this blog a place to record, for the benefit of myself and others, things I learn along the way and stuff that just isn’t so clearly presented on stackoverflow and the likes. I aim to discuss fun topics and present examples of code and how I used it for my specific purpose. I in know way expect to be correct in my usage all the time, but perhaps my stories will help lead others to the right answers.

cheers,

Jamie

Setting Sail