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
499 views
in Technique[技术] by (71.8m points)

reversing the order of an array in ruby

I have the following array [12,16,5,9,11,5,4] it prints: 12,16,5,9,11,5,4.

I want it to print: 4,5,11,9,5,16,12

When I did array.reverse it printed:

4,5,11,9,5,61,21

It reversed individual numbers - any idea how I can stop that?

question from:https://stackoverflow.com/questions/5241185/reversing-the-order-of-an-array-in-ruby

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

1 Reply

0 votes
by (71.8m points)
irb(main):001:0> a = [12,16,5,9,11,5,4]
=> [12, 16, 5, 9, 11, 5, 4]
irb(main):002:0> a.reverse
=> [4, 5, 11, 9, 5, 16, 12]

I'm not seeing what you're seeing.

Edit: Expanding on what Ben noticed, you may be reversing a string.

irb(main):005:0> "12,16,5,9,11,5,4".reverse
=> "4,5,11,9,5,61,21"

If you have to reverse a string in that manner, you should do something like the following:

irb(main):008:0> "12,16,5,9,11,5,4".split(",").reverse.join(",")
=> "4,5,11,9,5,16,12"

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

...