I have a test for which I need to write the code to make it pass. The test is this:
require 'lib/String.rb'
RSpec.describe String do
context '.to_h' do
let(:hash) { { 'hello' => 'tree' } }
it 'it should return the string parsed as a hash' do
expect(hash.to_s.gsub('=>', ':').to_h).to eq(hash)
end
it 'should raise parse error if there was a parsing error' do
expect { hash.to_s.to_h }.to raise_error(String::ParseError)
expect(String::Error).to be < StandardError
expect(String::ParseError).to be < String::Error
end
end
end
The code I wrote up till now is:
class String
class ParseError < StandardError
def initialize
String.const_set("Error", self)
end
end
def to_h
if self.split(":").count>1
eval(self.split(":")[0]+"=>"+self.split(":")[1])
else
raise ParseError
end
end
end
I must say that I am new to ruby so the code I wrote could be useless.
Aucun commentaire:
Enregistrer un commentaire