Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Magic Methods in Ruby?

Ruby enthusiasts! I am trying to write a DSL in ruby and i would like to be able to create some magic methods (not sure that is the most accurate term for what i want).

I would like to be able to do things like the following:

a = [1, 2, 3]
b = 2

(a contains b)

And have it resolve to true or false.

Essentially, how can i define the function "contains" so that it takes an array a and a variable b and performs a.contains?(b), but without all of the associated ruby-specific syntax?

like image 895
Elliot Cohen Avatar asked Feb 28 '26 10:02

Elliot Cohen


1 Answers

if you want a DSL that doesn't use ruby syntax, you need to write a parser at the very least to perform the transformation (raganwalds rewrite lib might be a starting point, http://github.com/raganwald/rewrite)

That said, you don't want to do this. This is more code to maintain and Ruby has already made a lot of the tough decisions that make writing a language syntax hard. Natural language programming also isn't much easier for nonprogrammers to use as the exactness of the format is the challenging aspect (see applescript for instance).

like image 191
Ben Hughes Avatar answered Mar 02 '26 01:03

Ben Hughes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!