r/badcode • evil • Jan 14 '21

js Dynamically created functions are the future!

Post image
795 Upvotes

102 comments sorted by

View all comments

74

u/[deleted] Jan 14 '21

In Ruby you can do this in a nice and useful way.

60

u/NotSteve_ evil Jan 14 '21

Haha seriously? What possible use could writing functions in strings have

77

u/[deleted] Jan 14 '21 edited Jan 14 '21

You can dynamically create methods. It's useful for reducing boilerplate. Sometimes you find yourself just having to implement almost identical methods. That's when it's useful to reach for Ruby's metaprogramming.

I've found it useful when doing Ruby and missed it using other languages that don't have it.

Not something you would use very often though.

4

u/Igotbored112 Jan 14 '21

I haven’t ever used Ruby before. Today I wrote 5 functions in C++ which all printed out an array, but they were each specialized for a specific primitive data type that the array might be holding. The functions all have the same name and are used identically by the library user because they’re specialized template functions. But they’re also virtually identical. It had to be this way because primitive types don’t really have special tostring functions in C++ (Well, they do if you use wrappers and the std::iostream class I think but I use printf because it’s way more readable and easy to use.)

In any case, do you think Ruby’s meta programming would have made that easier?

3

u/blueshiftlabs Jan 15 '21

1

u/Igotbored112 Jan 15 '21

Oh boy is it time for me to finally stop using char pointers everywhere?

1

u/[deleted] Jan 14 '21

Well, if you had them in the same class then yes. But then you wouldn't be able to name them the same thing. But other than that, you define the method, and then you can do whatever operations you want inside that method. Including printing or returning different things depending on values within a specific array.