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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…