Search code examples
rubymethodslanguage-featuresinfix-notationprefix-notation

How to use integer methods using `method`, not their infix form, in Ruby


I am looking to programmatically apply a typically infixed operation (eg: +, -, *, /) on two integers, where the operation is specified via a string. I have had success accessing the method itself using .method

This is a pattern that works, 1.+(2) which correctly resolves to 3

By extension, I'd to define a way that could take a variable string for the operator, like so: 1 + 2 as 1.method('+')(2)

The above causes a syntax error, though up til the point of retrieving the method this way does work, I'm not sure what the syntax needs to be to then pass the second integer argument. e.g:

1.method('+')     # <Method: Integer#+(_)>
1.method('+') 2   # syntax error, unexpected integer literal, expecting end-of-input
1.method('+')(2)  # syntax error, unexpected '(', expecting end-of-input

What is the right syntax to perform an operation 1 + 2 in this way?

I am using: ruby 3.1.2p20 (2022-04-12 revision 4491bb740a) [x86_64-linux]


Solution

  • The Method class has several instance method of it's own. The one you're looking for here is call

    It is also aliased to [] and ===

    1.method('+').call(2) #=> 3
    1.method('+')[2] #=> 3
    1.method('+') === 2 #=> 3