反转 Ruby 字符串,不使用 .reverse 方法

cpp*_*ick 1 ruby

我正在处理这个编码挑战,我发现我被卡住了。我认为可以对传入的参数调用 .string 方法,但现在我不确定。我在 Ruby 文档中发现的所有内容都表明并非如此。我真的很想在不看解决方案的情况下弄清楚这一点。有人可以帮助我朝正确的方向推动吗?

# Write a method that will take a string as input, and return a new
# string with the same letters in reverse order.
# Don't use String's reverse method; that would be too simple.
# Difficulty: easy.

def reverse(string)
string_array = []

string.split()

string_array.push(string)

string_array.sort! { |x,y| y <=> x}
end

# These are tests to check that your code is working. After writing
# your solution, they should all print true.

puts(
  'reverse("abc") == "cba": ' + (reverse("abc") == "cba").to_s
)
puts(
  'reverse("a") == "a": ' + (reverse("a") == "a").to_s
)
puts(
  'reverse("") == "": ' + (reverse("") == "").to_s
)
Run Code Online (Sandbox Code Playgroud)

Che*_*kar 5

反转字符串的最简单方法

s = "chetan barawkar"

b = s.length - 1

while b >= 0

  print  s[b]

  b=b-1

end
Run Code Online (Sandbox Code Playgroud)


col*_*ect 5

这是#reverse我遇到的最简单的单行解决方案,用于在不使用的情况下反转字符串-

"string".chars.reduce { |x, y| y + x }          # => "gnirts"
Run Code Online (Sandbox Code Playgroud)

另外,我从来没有听说过这种#string方法,我想你可以试试#to_s.