Home > Back-end >  What does parameter a and b mean in an array of elements in Ruby?
What does parameter a and b mean in an array of elements in Ruby?

Time:01-20

I'm practicing the sort function, the target is an array (ary) of a sentence. An example method I have seen is to build and use a block, and finally arrange the elements (words) in the array from short to long, and from a to z.

But I don't understand why there are two parameters a and b in this example, why should we find out a.length and b.length first? This is the original code:

ary = %w(
    Ruby is a open source programming language with a afocus on simplicity and productivity.
)

call_num = 0
sorted = ary.sort do |a, b|
    call_num  = 1
    a.length <=> b.length
end

puts "Sort results: #{sorted}" #=>["a", "a", "on", "is", "and", "Ruby", "open", "with", "afocus", "source", "language", "simplicity", "programming", "productivity."]
puts "Number of array elements: #{ary.length}" #=> 14
puts "Number of calls to blocks: #{call_num}" #=>30

CodePudding user response:

To sort the following array of words by their length Ruby has to basically compare each word in the array to each other word (Note that this is not exactly how sorting works internally but in the context of this example we can assume that sorting works like this).

ary = %w(
  Ruby is a open source programming language with a afocus on simplicity and productivity.
)

That means in the first step Ruby will need to compare the words Ruby and is and has to decide how to sort those two words, then is and a, then a and open.

Those two words in each step of the comparison are the two block parameters a and b. a.length <=> b.length will then tell Ruby how to sort those two parameters (words).

See Comparable and Enumerable#sort

  •  Tags:  
  • Related