0

I'm very new to ruby and I have been writing some simple programs. I've noticed that alot of my programs are creating no returned values when I try to run them through the command line, but seem to be working perfectly when I use repl.it for testing. For example:

def rev(a)

b = []

c = []

b = a.scan(/\w+/)

c = b.map {|x| x.reverse }

return c.join(' ')

end

rev('hello')

If I use puts c.join(' ') the answer will appear but it's not being returned which is what I need to happen. I have a feeling this is something very simple. Any help is appreciated, I've had to create some weird and blocky work arounds to make my other programs work but have limited what I've been able to do.

I'm making this program to fulfill some rspec specifications that were given to me, so simply printing or putting the answer isn't enough, I need the final term evaluated to be the answer.

4

3 回答 3

1

那是因为 repl.it 向您显示语句的结果,而 Ruby 不会自动执行此操作。

Ruby可以做到这一点,尝试找到名为“IRB”(代表“Interactive Ruby”)的程序。如果您将程序放入其中,您将获得所需的结果。

尽管您可以看到它确实在返回值:

puts(rev('hello'))

repl.it 只是自动向您显示最后一个表达式的结果。

在不相关的说明中,这里有一些提示:

  • 使用缩进 - 在您的代码中很难看出哪些行属于该函数
  • 将变量命名为描述性名称,以便以后阅读代码时知道它们的用途
  • 您不需要键入return,因为 Ruby 会自动返回最后一条语句
于 2013-08-15T00:41:37.330 回答
1

Ruby 方法自动返回最后一条语句的值。如果你改变

return c.join(' ')

puts c.join(' ')

它将尝试返回 的返回值puts,这不是您想要的。顺便说一句,return在这种情况下您可以省略。简单的说

c.join(' ')

作为最后一条语句,该方法将使用它作为返回值。

于 2013-08-15T00:43:07.673 回答
0

如果要获取方法的返回值,则必须将其存储在变量中:

answer = rev('hello')

如果你想看到答案——就像你在 IRB(“repl”)中所做的那样,那么你必须让 Ruby 输出它:

p answer    # Print the result of calling `answer.inspect`
puts answer # Print the result of calling `answer.to_s`
于 2013-08-15T03:17:46.383 回答