2

I've seen Ruby code in which there are only two double quotes ("") on a line. What does that line do?

Abhijeet Pathak
  • 1,948
  • 3
  • 20
  • 28
  • 1
    Could you show us an example of such code? As JesperE says, it returns an empty string. If you give us some context, we might be able to describe why you would want an empty string. – Brian Campbell Sep 06 '10 at 06:54

2 Answers2

5

I assume you might have seen a code like this.

def some_method
   #do some operations
   ""
end

In this context, it means that the method is returning an empty string. In Ruby, the last evaluated operation in a method is what is returned from that method. So in this case, it returns an empty string literal.

bragboy
  • 34,892
  • 30
  • 114
  • 171
  • Weird. I don't know Ruby, but it sounds like how lambdas behave in other languages. – mpen Sep 06 '10 at 07:02
  • @Mark : It was first weird to me as I used Java for many years, but I started to like Ruby very much now! Its pure fun.. – bragboy Sep 06 '10 at 07:22
  • Well, it's not so weird once you know that methods, if they reach their end statement, return the result of the last statement. The two double quotes is not very clear, however. Adding a return statement would at least say you intended to do that. Terseness is not always the best way. – AboutRuby Sep 06 '10 at 07:42
  • 1
    @AboutRuby: A single literal on a line (specifically, on a last line in a method) shows very clear intention IMHO. It's one of Ruby idioms. – Mladen Jablanović Sep 06 '10 at 08:46
2

Two double quotes represent an literal empty string in Ruby. And in many other languages.

JesperE
  • 63,317
  • 21
  • 138
  • 197