I am trying to get some clarification on why one line of code passes an rspec test and another does not. I was tasked with writing a method that sorted an array of strings by length. I tried to different sort options with different blocks be passed into the sort method. I think I may have figure it out in my comments on my code.
Does my commented out line of code not pass the test because it is literally only checking the length of a new item each time a new item is passed into the block instead of checking the length of an item against the lengths of the other items in the array of strings defined in the spec. If that makes sense..
My code is as follows:
def sort_by_length(sort_this_array)
#sort_this_array.sort {|item| item.length }
sort_this_array.sort {|x,y| x.length <=> y.length }
end
The RSpec is as follows:
describe "sort_by_length" do
it "sorts an array of strings by length" do
a = %w(z yyyy xxx ww)
sorted = %w(z ww xxx yyyy)
expect( sort_by_length(a) ).to eq(sorted)
end
it "sorts hashes by length" do
a = [{a: "a", b: "b"}, { key: "value"}, {}]
sorted = [{}, { key: "value"}, {a: "a", b: "b"}]
expect( sort_by_length(a) ).to eq(sorted)
end
end
describe "sort_by_length" do
it "sorts an array of strings by length" do
a = %w(z yyyy xxx ww)
sorted = %w(z ww xxx yyyy)
expect( sort_by_length(a) ).to eq(sorted)
end
it "sorts hashes by length" do
a = [{a: "a", b: "b"}, { key: "value"}, {}]
sorted = [{}, { key: "value"}, {a: "a", b: "b"}]
expect( sort_by_length(a) ).to eq(sorted)
end
end