austinthesing
austinthesing

Reputation: 725

Ruby String sorting method

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

Upvotes: 0

Views: 139

Answers (1)

Mischa
Mischa

Reputation: 43298

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 }

Upvotes: 2

Related Questions