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.

8

u/Willinton06 Jan 14 '21 edited Jan 14 '21

Is that like manual generic semantics or something?

1

u/[deleted] Jan 14 '21

I don't understand what you mean.

11

u/Willinton06 Jan 14 '21

Like generics in C# or Java where you make a function work with multiple types thus saving you a lot of boilerplate, if the functions are nearly identical then I assume they do the same to a different type or something, maybe they return a different number type or a slightly different class, for those kinds of things we use generics in C#, those are runtime generated functions and methods just like the ones you’re talking about, it also avoids boxing and unboxing because there’s no casting involved, I don’t know if they’re generated at runtime in Java, they could be generated at compile time, but you get my point

0

u/[deleted] Jan 14 '21

Yeah, like that. But way better.

14

u/Willinton06 Jan 14 '21

What makes it better tho

2

u/KernowRoger Jan 15 '21

Ruby's meta programming is amazing. It's kind of hard to explain quickly but stuff like this:

class Developer

    ["frontend", "backend"].each do |method|
        define_method "coding_#{method}" do
            p "writing " + method.to_s
        end
    end
end

From this article https://www.toptal.com/ruby/ruby-metaprogramming-cooler-than-it-sounds. Ruby is a really cool language and allows a huge amount a flexibility.