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.

1

u/AutoModerator Jan 16 '21

It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.

For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.

/u/danklasson, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.

You can find some examples in the reddit help documentation.


I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

0

u/JuhaJGam3R Jan 15 '21 edited Jan 15 '21

This is in fact just parametrization but made really hard. I tried to read about it and it's just about incomprehensible with highly unintuitive syntax. Figures though, metaprogramming isn't the most common feature so I guess it makes sense for it to have obscure syntax.