Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

Sorting a struct based on a reference array in ruby

I have a struct definition as

Player = Struct.new(:name, :level)

And a sample array

levels = [ 'level-1','level-2','beta','alpha','level4','level7']

I want to sort the struct in a way that the members appear in the increasing order of the levels mentioned eg

[#<struct Player name="Ryan", level="beta">,
 #<struct Player name="Chris", level="alpha">,
  #<struct Player name="Tom", level="level4">,
 #<struct Player name="Edward", level="level1">,
  #<struct Player name="Drew", level="level7">]

becomes

 #[<struct Player name="Edward", level="level1">,
 #<struct Player name="Ryan", level="beta">,
 #<struct Player name="Chris", level="alpha">,
  #<struct Player name="Tom", level="level4">,
  #<struct Player name="Drew", level="level7">]

How do I go about doing that in ruby.

I tried

arr.sort_by { |e| [ levels.index(e.level)] }

ArgumentError: comparison of Array with Array failed
from (pry):79:in `sort_by'

question from:https://stackoverflow.com/questions/65876219/sorting-a-struct-based-on-a-reference-array-in-ruby

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

1 Reply

0 votes
by (71.8m points)

You've almost got it. The result of the sort_by block should be what you want to compare against. You want to use the index in levels, not an Array which contains the index in levels.

arr.sort_by { |e| levels.index(e.level) }

And make sure you've got your level strings correct. You may wish to use constants to avoid typos.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...