1

我是 ruby​​ 新手,这可能是一个显而易见的问题,但我真的不知道在 Google 上搜索什么才能真正找到我正在寻找的东西。

我正在做算法问题(不是很相关),它给了我一个方阵,并询问它是否具有圆对称性。我这样解决它:

s = STDIN.readlines.map { |x| x.chomp }.join ''
puts %w[YES NO][s == s.reverse ? 0 : 1]

是否可以将所有这些放在一行中?我不能的唯一原因是因为我认为我必须存储字符串,然后稍后显式比较它。它从 STDIN 获取字符串,所以我无法重新读取它。任何优雅的解决方案?谢谢!

4

2 回答 2

2

Object#tap takes a block, and passes the object to that block. Thus, should be able to rewrite that as:

STDIN.readlines.map { |x| x.chomp }.join('').tap { |s| puts %w[YES NO][s == s.reverse ? 0 : 1] }

Although I agree with the commenter that this is only going to hurt readability.

于 2013-02-03T01:33:31.263 回答
0

Disregarding readability, you can almost always force things on to a single line by using the ; separator.

In your case since s is referenced twice you need to assign it to a variable.

于 2013-02-03T01:32:01.293 回答