Tag: 字符串

Ruby将不可打印的字符转换为数字

我有一个包含不可打印字符的字符串。 我目前正在做的是用波浪号代替它们: string.gsub!(/^[:print:]]/, “~”) 但是,我实际上想将它们转换为整数值。 我试过这个,但总是输出0 string.gsub!(/[^[:print:]]/, “#{$1.to_i}”) 思考?

如何在不使用eval的情况下将字符串转换为ruby / rails中的哈希?

这是需要转换为hash的string 。 “{:status => {:label => ‘Status’, :collection => return_misc_definitions(‘project_status’) } }” 我们不能使用eval因为eval将在字符串中执行return_misc_definitions(‘project_status’)方法。 是否有纯字符串操作来完成ruby / rails中的这种转换? 感谢帮助。

Ruby Koans:此返回值的引号在哪里?

我正在研究以下Ruby Koan: class Dog7 attr_reader :name def initialize(initial_name) @name = initial_name end def get_self self end def to_s __ end def inspect “” end end def test_inside_a_method_self_refers_to_the_containing_object fido = Dog7.new(“Fido”) fidos_self = fido.get_self assert_equal “”, fidos_self end def test_to_s_provides_a_string_version_of_the_object fido = Dog7.new(“Fido”) assert_equal __, fido.to_s end 第一个assert_equal的前半部分是我想填写的。这段代码给出了错误: <"”> expected but was <>. 问题是,我坚持如何匹配返回值。 它看起来像一个字符串文字返回值,但我不知道如何在不使用引号和/或反斜杠的情况下表达它。 我没有尝试似乎工作。 […]

在Ruby中构建长字符串的干净方法

在编写Ruby(客户端脚本)时,我看到了三种构建更长字符串的方法,包括行结尾,所有这些对我来说都“难闻”。 有没有更清洁,更好的方法? 变量递增。 if render_quote? quote = “Now that there is the Tec-9, a crappy spray gun from South Miami.” quote += “This gun is advertised as the most popular gun in American crime. Do you believe that shit?” quote += “It actually says that in the little book that comes with it: the most […]

Ruby / Rails中是否有<<< EOD?

在PHP中,以下内容允许我创建一个字符串而不必转义引号。 $string = <<<EOD ',. whatever <"",' EOD; echo $string; Ruby / Rails中有类似的东西吗?

反斜杠打破了ruby中的字符串插值

我想最后得到字符串”/a_setting/c\blah = something” ,其中属性被评估为其值:blah。 但是,我看到以下行为,其中前面的反斜杠似乎停止了对变量的评估: attribute = “blah” “/a_setting/c\#{attribute} = something” => “/a_setting/c\#{attribute} = something” “/a_setting/c\ #{attribute} = something” => “/a_setting/c blah = something”

Ruby String:如何从定义的位置匹配Regexp

我想仅从定义的位置匹配来自ruby字符串的正则表达式。 那个位置之前的比赛对我不感兴趣。 而且,我想要\A来匹配这个位置。 我找到了这个解决方案 code[index..-1][/\A[a-z_][a-zA-Z0-9_]*/] 这匹配字符串code中位置index的正则表达式。 如果匹配不完全在位置index ,则返回nil 。 有没有更优雅的方法来做到这一点(我想避免用第一个切片创建临时字符串)? 谢谢

在Ruby中将整数字符串转换为字节数组

我有一个整数字符串“72101108108111”,但它是一个字符串,表示原始字符串“Hello”的字节。 如何在Ruby中将“72101108108111”转换为Ascii字符串“Hello”?

Ruby删除与数组的任何元素匹配的子字符串

我有一个字符串说str =”this is the string ” ,我有一个字符串数组说 array =[“this is” ,”second element”, “third element”] 我想处理字符串,以便匹配任何数组元素的子字符串应该被删除,其余的字符串应该返回。所以我想要以下输出。 output: “the string ” 我怎么能在ruby中这样做。

如何从JSON字符串中删除反斜杠?

我有一个JSON字符串,如下所示 ‘{\”test\”:{\”test1\”:{\”test1\”:[{\”test2\”:\”1\”,\”test3\”: \”foo\”,\”test4\”:\”bar\”,\”test5\”:\”test7\”}]}}}’ 我需要使用Ruby或Rails将其更改为下面的一个: ‘{“test”:{“test1”:{“test1”:[{“test2″:”1″,”test3”: “foo”,”test4″:”bar”,”test5″:”bar2″}]}}}’ 我需要知道如何删除这些斜杠。