0

I saw this example in an answer elsewhere and with the following it outputs foobar:

a = :foo

def bar(b)
  :"#{b}bar"
end

c = bar(a)

c       
John C.
  • 63
  • 1
  • 6

1 Answers1

8

The colon isn't an operator inside bar, it is simply a Symbol literal that uses string interpolation to build the Symbol. Some Symbols need to be quoted to avoid syntax issues, for example:

:'a+b'

You can also use double quotes with this syntax and those quotes behave just like double quotes for strings so they support string interpolation. So this:

:"#{b}bar"

is equivalent to:

"#{b}bar".to_sym

or

(b.to_s + 'bar').to_sym

If you #inspect your value you'll get a better idea of what it contains:

puts c.inspect
# :foobar
mu is too short
  • 426,620
  • 70
  • 833
  • 800
  • It’s worth it to mention that “it is setting variable as a reference” wording in OP is wrong and confusing. – Aleksei Matiushkin Aug 20 '18 at 04:12
  • 1
    @mudasobwa I saw that as a confusing and "not their best ever" use of English so going down that rabbit hole would be a distraction. – mu is too short Aug 20 '18 at 04:58
  • You are right about variable as a reference. I got it from here: https://stackoverflow.com/questions/39203911/how-to-pass-by-reference-in-ruby. It is clear that the example, where I took this from, had nothing to do with pass by reference. – John C. Aug 21 '18 at 17:07
  • 1
    I removed the confusing lines at the end. Thanks for the answer! – John C. Aug 21 '18 at 17:09