2

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`
jleeothon
  • 2,907
  • 4
  • 19
  • 35
  • 2
    Hint: if you want to call a method named `foo` with arguments, how do you do that? – Jörg W Mittag Mar 21 '19 at 09:45
  • How does `bar` work? – Sagar Pandya Mar 21 '19 at 10:37
  • You must use `Foo.new.send(:\`, "hello_world")` but I assume that is not why you're trying to do this and you're trying to safely parse/eval some template. Sorry to say, but that is probably going to be a lot harder than you would think. The user could still use `::Kernel.send(:\`, 'foo')` or many many other tricks. – Kimmo Lehto Mar 21 '19 at 11:20
  • @KimmoLehto: There is no reason to use `send`. You can use normal method calling syntax. The problem is simply that the OP does not seem to understand what a normal method call in Ruby looks like. – Jörg W Mittag Mar 21 '19 at 11:42
  • @KimmoLehto: Using `send` is actually only in `irb`. As @JörgWMittag says it works fine in `rb`-file without `send` – mechnicov Mar 21 '19 at 12:38
  • I'm not trying to use this in production to e.g. do anything with templates. Just trying to understand Ruby's parser more thoroughly. – jleeothon Mar 21 '19 at 13:34

1 Answers1

2

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')
E_net4
  • 27,810
  • 13
  • 101
  • 139
mechnicov
  • 12,025
  • 4
  • 33
  • 56
  • It doesn't work, at least in 2.6.1 `irb`. And even if it did, it's not "alternate syntax for backtick". – Marek Lipka Mar 21 '19 at 12:04
  • @MarekLipka. It doesn't work in `irb`. But did you try to use this code in file says `backtricks.rb` and then run `ruby backtricks.rb`? It works. I edited my answer. – mechnicov Mar 21 '19 at 12:34
  • Thanks for clarifying that this won't work in `irb`. I see this as a shortcoming of irb's as opposed to this not being the properly-meant method-like (as opposed to operator-like) syntax. – jleeothon Mar 21 '19 at 13:35
  • 1
    @MarekLipka: IRb is well-known to be broken in various ways since it uses its own hand-written, not quite Ruby-compliant parser. – Jörg W Mittag Mar 21 '19 at 14:27