DEV Community

Discussion on: Daily Challenge #37 - Name Swap

Collapse
 
mwlang profile image
Michael Lang • Edited

Ruby Language

Robust version and with test specs!

def name_shuffler name
  name.to_s.strip.split(/\s+/).reverse.join(" ")
end

require "spec"

describe "#name_shuffler" do
  it { expect(name_shuffler "Foo Bar").to eq "Bar Foo"}
  it { expect(name_shuffler "Foo    Bar").to eq "Bar Foo"}
  it { expect(name_shuffler "   Foo Bar").to eq "Bar Foo"}
  it { expect(name_shuffler "Foo Bar   ").to eq "Bar Foo"}
  it { expect(name_shuffler "Foo").to eq "Foo"}
  it { expect(name_shuffler "   Foo").to eq "Foo"}
  it { expect(name_shuffler "Foo   ").to eq "Foo"}
  it { expect(name_shuffler "").to eq ""}
  it { expect(name_shuffler nil).to eq ""}
  it { expect(name_shuffler 777).to eq "777"}
end

output

>> rspec name_shuffler.rb
..........

Finished in 0.0059 seconds (files took 0.15188 seconds to load)
10 examples, 0 failures