Skip to content

Instantly share code, notes, and snippets.

@jamesshipton
Last active October 13, 2015 18:07
Show Gist options
  • Save jamesshipton/4234874 to your computer and use it in GitHub Desktop.
Save jamesshipton/4234874 to your computer and use it in GitHub Desktop.
Please rewrite the MyString definition, without using ruby keywords # http://www.ruby-doc.org/docs/keywords/1.9/
# 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
require 'rspec/autorun'
describe MyString do
describe '.alphabet' do
specify { MyString.alphabet.should == 'abc' }
end
describe '#exclaim' do
subject { MyString.new('james') }
specify { subject.exclaim.should == 'james!' }
specify { subject.exclaim(4).should == 'james!!!!' }
end
describe '#!' do
subject { MyString.new('james') }
specify { subject.!.should == 'james!' }
it 'should be the same even if #exclaim is redefined' do
MyString.class_eval { define_method(:exclaim) { '' } }
subject.!.should == 'james!'
end
end
describe '#exclamation_mark' do
specify { subject.should_not respond_to(:exclamation_mark) }
end
end
MyString = Class.new(String)
MyString.define_singleton_method(:alphabet, lambda { 'abc' })
MyString.send(:define_method, :exclaim, lambda { |count = 1| "#{self}#{exclamation_mark count}" })
MyString.send(:define_method, :exclamation_mark, lambda { |count| '!' * count })
MyString.send(:alias_method, :!, :exclaim)
MyString.send(:private, :exclamation_mark)
require 'rspec/autorun'
describe MyString do
describe '.alphabet' do
specify { MyString.alphabet.should == 'abc' }
end
describe '#exclaim' do
subject { MyString.new('james') }
specify { subject.exclaim.should == 'james!' }
specify { subject.exclaim(4).should == 'james!!!!' }
end
describe '#!' do
subject { MyString.new('james') }
specify { subject.!.should == 'james!' }
it 'should be the same even if #exclaim is redefined' do
MyString.class_eval { define_method(:exclaim) { '' } }
subject.!.should == 'james!'
end
end
describe '#exclamation_mark' do
specify { subject.should_not respond_to(:exclamation_mark) }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment