FOOBAR in Ruby Here’s how I solved the FOOBAR challenge using Ruby and why I did it this way. If you’re unfamiliar with this challenge, you’re goal is to have the computer print out a…
Browsing Category Ruby
The difference between select and map methods
Here is a basic understanding of the .select and .map methods with real world analogies and coding examples. .select takes a block and creates a new array of the items the block evaluates to true…
Building a Deck of Cards in Ruby
I would like to share this challenge I did while at The Firehose Project online bootcamp. The challenge: Build a deck of cards, shuffle them, and deal a card. The code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
class Card attr_accessor :rank, :suit def initialize(rank, suit) @rank = rank @suit = suit end def output_card puts "The #{@rank} of #{@suit}" end end class Deck def initialize @ranks = [*(2..10), 'J', 'Q', 'K', 'A'] @suits = ['♣', '♥', '♠', '♦'] @cards = [] @ranks.each do |rank| @suits.each do |suit| @cards << Card.new(rank, suit) end end @cards.shuffle! end def deal (number) number.times {@cards.shift.output_card} end end deck = Deck.new deck.deal(7) |
Thought process First,…
Explaining the inject method
The inject method takes a collection and reduces it to a single value, such as a sum of values. Here are the basic workings when iterating through an array and adding the elements together:
1 2 3 4 5 6 |
def numbers(array) array.inject {|element1, element2| element1 + element2} end numbers([1, 2, 3, 4, 5]) => 15 |
What’s…