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

Categories

If I have this array:

["A", "B", "C", "D"]

I have this string:

"C"

I want to reorder the array to look like this:

["C", "A", "B", "D"]

So, the passed in string will move the matching element to the front of the list.

See Question&Answers more detail:os

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

1 Answer

a = ['A', 'B', 'C', 'D', 'C']
target = 'C'

a.partition { |e| e==target }.reduce(:+)
  #=> ["C", "C", "A", "B", "D"]

or

a.select { |e| e==target }.concat(a.reject { |e| e==target })
  #=> ["C", "C", "A", "B", "D"]

a is not modified.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...