Skip to content

Instantly share code, notes, and snippets.

View pwightman's full-sized avatar

Parker Wightman pwightman

View GitHub Profile
1.9.3p194 :006 > u.errors[:title] = "can't be blank"
=> "can't be blank"
1.9.3p194 :007 > u.errors.full_messages
=> ["Title can't be blank"]
1.9.3p194 :008 > u.errors[:base] = "Please don't do that"
=> "Please don't do that"
1.9.3p194 :009 > u.errors.full_messages
=> ["Title can't be blank", "Please don't do that"]
class CartesianProduct
include Enumerable
def initialize a, b
@a = a
@b = b
end
# Every method has an implied block that is sent into it, it does NOT need to be
# specified as a parameter.
# (a)
class Class
def attr_accessor_with_history attr
attr = attr.to_s
attr_reader attr
class_eval %Q{
# Create a history method for the attribute
class Dessert
attr_accessor :name, :calories
def initialize(name, calories)
@name = name
@calories = calories
end
def healthy?
@calories < 200
def combine_anagrams words
# Kendal's idea. Passing a block to the constructor is how you tell
# the hash what to do when a key is accessed that doesn't yet exist.
hash = Hash.new do |h, key|
h[key] = []
end
words.each do |word|
# As the key, we want to use the lowercase sorted
# for of the word, as anagrams will always have the
class WrongNumberOfPlayersError < StandardError ; end
class NoSuchStrategyError < StandardError ; end
def rps_game_winner(game)
raise WrongNumberOfPlayersError unless game.length == 2
player1 = game[0]
player2 = game[1]
player1_play = player1[1]
def palindrome? str
str.downcase!
# gsub stands for "global substitution" and replaces all occurrences
# of the matching regex with the given string. Here, we want all "non-word"
# characters to be removed from the string
str.gsub! /[\W]/, ""
# If the forward and backward versions are the same, it's a palindrome
str == str.reverse
end