Reverse a string in Ruby

前端 未结 22 1084
广开言路
广开言路 2020-12-05 06:36

How do you reverse a string in Ruby? I know about string#reverse. I\'m interested in understanding how to write it in pure Ruby, preferably an in-place solution.

22条回答
  •  情话喂你
    2020-12-05 07:09

    A simple classic way with n/2 complexity

    str = "Hello World!";
    puts str;
    
    for i in 0..(str.length/2).to_i
      mid = (str.length-1-i);
      temp = str[i];
      str[i] = str[aa];
      str[aa] = temp;
    end
    
    puts str;
    

提交回复
热议问题