Reputation: 101
I'm new to ruby, and this might be an obvious question but I really have no idea what to search for on Google to actually find what I'm looking for.
I'm doing algorithmic problems (not really relevant), and it gives me a square matrix, and asks if it has circular symmetry. I solve it like this:
s = STDIN.readlines.map { |x| x.chomp }.join ''
puts %w[YES NO][s == s.reverse ? 0 : 1]
Is it possible to put all that in one line? The only reason I can't is because I think I have to store the string and then explicitly compare it later. And it sources the string from STDIN so I can't re-read it. Any elegant solutions? Thanks!
Upvotes: 1
Views: 82
Reputation: 258138
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.
Upvotes: 2
Reputation: 211540
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.
Upvotes: 0