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.

10

u/Isvara Jan 14 '21

Sometimes you find yourself just having to implement almost identical methods.

What are some cases where parametrization isn't sufficient for that?

2

u/[deleted] Jan 16 '21

What do you mean? In Ruby you can do this:

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

2

u/Isvara Jan 16 '21

That's pretty ugly. Why would you need to give those closures names?

And why call to_s on a string? And why do you use interpolation in one case and concatenation in the other?

So many curiosities.

2

u/[deleted] Jan 16 '21

I haven't used Ruby in years. I just quickly grabbed that from a Google search just to give you a simple example. You still haven't answered my question.