奇怪的反转字符串

| 我试图不使用反向函数,类和数组来反向字符串。但是我正在尝试使用正则表达式。我使用程序员记事本编写程序。当我运行以下给定的代码时,它没有显示任何结果。我试图在每个循环的第七或第八个位置插入一个句点(。),以相反的顺序获取下一个字符。
s = \"This is to test reverse of a string\"
len = s.length
for j in len..1 do
    mycommand = \"s.scan(/.$/) {|x| puts x}\"
    mycommand = mycommand.insert 7,\".\"
end
    
已邀请:
好吧,目前尚不清楚您要做什么,但是这里有一些要点: 因为您在循环(块)中声明了\'mycommand \'变量-它仅在块中可见。意思是说,您将无法在其他任何地方使用它。现在,每次迭代都会创建\“ mycommand \”变量 此处:
for j in len..1 do
您的\'len \'变量(35)大于1。不会发生迭代,您应该像这样使用它     对于1..len中的j 这里:
mycommand = \"s.scan(/.$/) {|x| puts x}\"
您将mycommand声明为字符串(只是一组字符) 因此,当您声明:
mycommand = mycommand.insert 7,\".\"
红宝石将按照以下方式转换您的字符串:\“ s.scan(./.$/){| x |放x} \” 这个概念还不是很清楚,但是我认为您正在尝试做的是:
s = \"This is to test reverse of a string\"
len = s.length
mycommand = \"s.scan(/.$/) {|x| print x}\" # This does not execute a command, you just create a string
for j in len..1 do
  eval mycommand # Now this executes your command. Take a time and google for \"ruby eval\"
  s.chop! # This removes last character from your string. e.g \'hello\'.chop! #=> \'hell\'  
end
    
您不能使用downto。这项工作有5种方法。我不太清楚您要从这行line6 what理解什么,但它也会颠倒字符串:
s = \"This is to test reverse of a string\"
len = s.length
len.downto(1) do |j|
  s.scan(/.$/) {|x| puts x}
  s.chop!
end
    
s=\"abc\"
(s.size-1).downto(0).map{|x|s[x]}.join
    
以下1个班轮将解决问题:
> \"test reverse of a string\".scan(/./).inject([]) {|n,v| n.unshift v}.join
  => \"gnirts a fo esrever tset\" 
或更简洁地:
> \"test reverse of a string\".scan(/./).inject(\"\") {|n,v| n = v + n}
 => \"gnirts a fo esrever tset\" 
这将根据您的要求反转字符串。 我没有想过您问题的最后一部分,即在第7位和第8位之间插入,因此我没有尝试回答这一部分。     

要回复问题请先登录注册