Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
768 views
in Technique[技术] by (71.8m points)

ruby-on-rails - 红宝石中的自定义排序方法(custom sort method in ruby)

I want to specify a custom block method to sort an object array in ruby, by evaluating two properties.

(我想通过评估两个属性来指定一个自定义块方法来对Ruby中的对象数组进行排序。)

However after many searches in google I didn't get to any example without the <=> operator.

(但是,在Google中进行了许多搜索之后,没有<=>运算符,我就找不到任何示例。)

This is what i want to do: comparing a vs b:

(这就是我想做的:比较a与b:)

if a.x less than b.x return -1
if a.x greater than b.x return 1
if a.x equals b.x, then compare by another property , like a.y vs b.y

this is my code (noob in ruby, sorry) and it doesnt work...

(这是我的代码(Ruby中的菜鸟,对不起),它不起作用...)

ar.sort! do |a,b|
   if a.x < b.y return -1
   elseif a.x > b.x return 1
   else return a.y <=> b.y
end

This block is within a function so the return is geting out of the function and returning -1... I'll appreciate any help on this.

(该块位于函数内,因此返回值已退出函数并返回-1 ...我将不胜感激。)

Kind regards.

(亲切的问候。)

  ask by alexserver translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

这将给您从x到y的升序:

points.sort_by{ |p| [p.x, p.y] }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...