Skip to content

Instantly share code, notes, and snippets.

@lmars
Forked from jamesshipton/my_class_keywords.rb
Last active December 11, 2015 10:09
Show Gist options
  • Save lmars/4585020 to your computer and use it in GitHub Desktop.
Save lmars/4585020 to your computer and use it in GitHub Desktop.
#
# start of solution
#
MyString = Class.new(String)
MyString.define_singleton_method(:alphabet) { 'abc' }
MyString.class_eval {
exclaim_method = proc { |*args|
count = args.first || 1
"#{to_s}#{exclamation_mark count}"
}
define_method :exclaim, exclaim_method
define_method :!, exclaim_method
define_method(:exclamation_mark) { |count|
'!' * count
}
private :exclamation_mark
}
#
# end of solution
#
require 'rspec/autorun'
describe MyString do
describe '.alphabet' do
specify { MyString.alphabet.should == 'abc' }
end
describe '#exclaim' do
subject { MyString.new('lewis') }
specify { subject.exclaim.should == 'lewis!' }
specify { subject.exclaim(4).should == 'lewis!!!!' }
end
describe '#!' do
subject { MyString.new('lewis') }
specify { subject.!.should == 'lewis!' }
it 'should be the same even if #exclaim is redefined' do
MyString.class_eval { define_method(:exclaim) { '' } }
subject.!.should == 'lewis!'
end
end
describe '#exclamation_mark' do
specify { subject.should_not respond_to(:exclamation_mark) }
end
end
# Please rewrite the MyString definition, without using ruby keywords
# http://www.ruby-doc.org/docs/keywords/1.9/
class MyString < String
class << self
def alphabet
'abc'
end
end
def exclaim(count = 1)
"#{self}#{exclamation_mark count}"
end
alias :! :exclaim
private
def exclamation_mark(count)
'!' * count
end
end
j = MyString.new('james')
j.exclaim # "james!"
j.exclaim(4) # "james!!!!"
j.! # "james!"
MyString.alphabet # "abc"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment