Ruby remove interpolation from string












0















I want to remove string interpolation for eval.



I have a lot of places with such code, so only one option is modifying the condition to unescape code.



I found a regexp that works well



"#{user.name}"[/[^#{}]+/]


as result, I have "user.name"



but such code removing curly braces in blocks as well



"#{[1,2,3].map { |el| el }.join(',')}"[/[^#{}]+/]


returns



"[1,2,3].map "


the expected result is:



"[1,2,3].map { |el| el }.join(',')"


Any ideas how to solve it?










share|improve this question























  • Try your_str[/#({(?:[^{}]++|g<1>)*})/, 1].gsub(/[{}]/, ""), see demo.

    – Wiktor Stribiżew
    Nov 20 '18 at 13:18








  • 2





    If the goal of this is to make eval safe, don't bother. You would basically need to implement a Ruby static analyzer to truly do that.

    – Max
    Nov 20 '18 at 14:26
















0















I want to remove string interpolation for eval.



I have a lot of places with such code, so only one option is modifying the condition to unescape code.



I found a regexp that works well



"#{user.name}"[/[^#{}]+/]


as result, I have "user.name"



but such code removing curly braces in blocks as well



"#{[1,2,3].map { |el| el }.join(',')}"[/[^#{}]+/]


returns



"[1,2,3].map "


the expected result is:



"[1,2,3].map { |el| el }.join(',')"


Any ideas how to solve it?










share|improve this question























  • Try your_str[/#({(?:[^{}]++|g<1>)*})/, 1].gsub(/[{}]/, ""), see demo.

    – Wiktor Stribiżew
    Nov 20 '18 at 13:18








  • 2





    If the goal of this is to make eval safe, don't bother. You would basically need to implement a Ruby static analyzer to truly do that.

    – Max
    Nov 20 '18 at 14:26














0












0








0








I want to remove string interpolation for eval.



I have a lot of places with such code, so only one option is modifying the condition to unescape code.



I found a regexp that works well



"#{user.name}"[/[^#{}]+/]


as result, I have "user.name"



but such code removing curly braces in blocks as well



"#{[1,2,3].map { |el| el }.join(',')}"[/[^#{}]+/]


returns



"[1,2,3].map "


the expected result is:



"[1,2,3].map { |el| el }.join(',')"


Any ideas how to solve it?










share|improve this question














I want to remove string interpolation for eval.



I have a lot of places with such code, so only one option is modifying the condition to unescape code.



I found a regexp that works well



"#{user.name}"[/[^#{}]+/]


as result, I have "user.name"



but such code removing curly braces in blocks as well



"#{[1,2,3].map { |el| el }.join(',')}"[/[^#{}]+/]


returns



"[1,2,3].map "


the expected result is:



"[1,2,3].map { |el| el }.join(',')"


Any ideas how to solve it?







ruby regex






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 20 '18 at 12:36









Ivan VerevkinIvan Verevkin

274




274













  • Try your_str[/#({(?:[^{}]++|g<1>)*})/, 1].gsub(/[{}]/, ""), see demo.

    – Wiktor Stribiżew
    Nov 20 '18 at 13:18








  • 2





    If the goal of this is to make eval safe, don't bother. You would basically need to implement a Ruby static analyzer to truly do that.

    – Max
    Nov 20 '18 at 14:26



















  • Try your_str[/#({(?:[^{}]++|g<1>)*})/, 1].gsub(/[{}]/, ""), see demo.

    – Wiktor Stribiżew
    Nov 20 '18 at 13:18








  • 2





    If the goal of this is to make eval safe, don't bother. You would basically need to implement a Ruby static analyzer to truly do that.

    – Max
    Nov 20 '18 at 14:26

















Try your_str[/#({(?:[^{}]++|g<1>)*})/, 1].gsub(/[{}]/, ""), see demo.

– Wiktor Stribiżew
Nov 20 '18 at 13:18







Try your_str[/#({(?:[^{}]++|g<1>)*})/, 1].gsub(/[{}]/, ""), see demo.

– Wiktor Stribiżew
Nov 20 '18 at 13:18






2




2





If the goal of this is to make eval safe, don't bother. You would basically need to implement a Ruby static analyzer to truly do that.

– Max
Nov 20 '18 at 14:26





If the goal of this is to make eval safe, don't bother. You would basically need to implement a Ruby static analyzer to truly do that.

– Max
Nov 20 '18 at 14:26












1 Answer
1






active

oldest

votes


















2














You can use gsub and named regex in this case



> reg = Regexp.new('\#{(?<content>.+)}')
=> /#{(?<content>.+)}/
> str1.gsub(reg) { |match| $~[:content] }
=> "user.name"
> str2.gsub(reg) { |match| $~[:content] }
=> "[1,2,3].map { |el| el }.join(',')"


Your example didn't work well because [^smth] matches against any single character in the list, not the whole sentence.



BTW I'd like to warn you that regexp might fit for simple adjustments, but it will always have some edge cases. I'm not sure how the example above will behave on interpolation inside interpolation for example.



It's better to use proper lexer & parser for more complex cases.



Also, be very... very careful doing eval






share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53393144%2fruby-remove-interpolation-from-string%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














    You can use gsub and named regex in this case



    > reg = Regexp.new('\#{(?<content>.+)}')
    => /#{(?<content>.+)}/
    > str1.gsub(reg) { |match| $~[:content] }
    => "user.name"
    > str2.gsub(reg) { |match| $~[:content] }
    => "[1,2,3].map { |el| el }.join(',')"


    Your example didn't work well because [^smth] matches against any single character in the list, not the whole sentence.



    BTW I'd like to warn you that regexp might fit for simple adjustments, but it will always have some edge cases. I'm not sure how the example above will behave on interpolation inside interpolation for example.



    It's better to use proper lexer & parser for more complex cases.



    Also, be very... very careful doing eval






    share|improve this answer






























      2














      You can use gsub and named regex in this case



      > reg = Regexp.new('\#{(?<content>.+)}')
      => /#{(?<content>.+)}/
      > str1.gsub(reg) { |match| $~[:content] }
      => "user.name"
      > str2.gsub(reg) { |match| $~[:content] }
      => "[1,2,3].map { |el| el }.join(',')"


      Your example didn't work well because [^smth] matches against any single character in the list, not the whole sentence.



      BTW I'd like to warn you that regexp might fit for simple adjustments, but it will always have some edge cases. I'm not sure how the example above will behave on interpolation inside interpolation for example.



      It's better to use proper lexer & parser for more complex cases.



      Also, be very... very careful doing eval






      share|improve this answer




























        2












        2








        2







        You can use gsub and named regex in this case



        > reg = Regexp.new('\#{(?<content>.+)}')
        => /#{(?<content>.+)}/
        > str1.gsub(reg) { |match| $~[:content] }
        => "user.name"
        > str2.gsub(reg) { |match| $~[:content] }
        => "[1,2,3].map { |el| el }.join(',')"


        Your example didn't work well because [^smth] matches against any single character in the list, not the whole sentence.



        BTW I'd like to warn you that regexp might fit for simple adjustments, but it will always have some edge cases. I'm not sure how the example above will behave on interpolation inside interpolation for example.



        It's better to use proper lexer & parser for more complex cases.



        Also, be very... very careful doing eval






        share|improve this answer















        You can use gsub and named regex in this case



        > reg = Regexp.new('\#{(?<content>.+)}')
        => /#{(?<content>.+)}/
        > str1.gsub(reg) { |match| $~[:content] }
        => "user.name"
        > str2.gsub(reg) { |match| $~[:content] }
        => "[1,2,3].map { |el| el }.join(',')"


        Your example didn't work well because [^smth] matches against any single character in the list, not the whole sentence.



        BTW I'd like to warn you that regexp might fit for simple adjustments, but it will always have some edge cases. I'm not sure how the example above will behave on interpolation inside interpolation for example.



        It's better to use proper lexer & parser for more complex cases.



        Also, be very... very careful doing eval







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 20 '18 at 14:04

























        answered Nov 20 '18 at 13:58









        Alexey SuslyakovAlexey Suslyakov

        5421614




        5421614
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53393144%2fruby-remove-interpolation-from-string%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Guess what letter conforming each word

            Port of Spain

            Run scheduled task as local user group (not BUILTIN)