escaping a string in Ruby

后端 未结 4 583
有刺的猬
有刺的猬 2021-02-05 16:39

I want to insert the following as the value for a variable in some Ruby:

`~!@#$%^&*()_-+={}|[]\\:\";\'<>?,./

Surrounding this in doub

4条回答
  •  情话喂你
    2021-02-05 17:30

    The first thing I'd normally think of would be a %q directive -- but since you seem to be using all the punctuation you'd normally use to delimit one, I can't think of an easy way to make it work here.

    The second thing I'd think of would be a heredoc:

    mystring = <?,./
    END
    

    That breaks after the backslash, though.

    So my third answer, clunky but the best thing I can think of with just two minutes' thought, would be to substitute something harmless for the "problem" characters and then substitute it after the assignment:

    mystring = '`~!@#$%^&*()_-+={}|[]\:"; <>?,./'.tr(" ","'")
    

    I don't like it, but it works.

提交回复
热议问题