0

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

1 Answer 1

2

When using sort you always have to compare two variables and return -1, 0 or 1. From the documentation:

The block must implement a comparison between a and b, and return -1, when a follows b, 0 when a and b are equivalent, or +1 if b follows a.

In your commented out line you're not doing that. If you use sort_by, you can use that syntax:

 array.sort_by { |item| item.length }
Sign up to request clarification or add additional context in comments.

1 Comment

Note also that sort_by is faster, since it only evaluates item.length once per item (n times); sort will evaluate item.length twice per comparison (so, around 2*n*log(n) times). You should only use sort if the comparator function is complex. And further, note that you can write this specific case even more concisely as array.sort_by(&:length).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.