jleeothon
jleeothon

Reputation: 3166

Is there an alternate syntax in Ruby for backticks?

In Ruby you can do a + b, which is equivalent to a.+(b).

You can also override the +() method with def +(other); end.

Is there an alternate syntax for backticks? I know that this works:

class Foo
  def `(message)
    puts '<' + message + '>'
  end

  def bar
    `hello world`
  end
end

Foo.new.bar # prints "<hello world>"

But this won't work e.g.

Foo.new.`hello world`

Upvotes: 2

Views: 207

Answers (1)

mechnicov
mechnicov

Reputation: 15372

There is no difference between .+ and backticks

From the context, message is String. So use quotation marks.

class Foo
  def `(message)
    puts '<' + message + '>'
  end
end

Foo.new.` 'hello world' #prints <hello world>

Due to codestyle is better to use parentheses

Foo.new.`('hello world') #prints <hello world>

This code works perfectly in rb-file.

One might say that it doesn't work in irb. But irb is not a panacea (e.g. if you use . in the start of line, not in the end). So if you want to use it in irb, call it as

Foo.new.send(:`, 'hello world')

Upvotes: 2

Related Questions