Tag:

Unescaping Ruby字符串中的特殊字符序列

我正在从包含如下序列的文件中加载文本: abc\ndef\tghi 我想’unescape’所有特殊字符,例如将\n视为换行符和\t作为制表符等,而不是自动以字符串中的\\n或\\t结尾。 是否有捷径可寻?

Ruby字符串中的自定义+方法

我试图修改Ruby String类,特别是+方法。 我希望它返回一个特定的字符串,这样 “a” + “b” => “custom_result” 这就是我所拥有的: class String def +(a) “custom_result” end end 当我尝试在irb中要求此文件时,“custom_result”在我的提示符中,我无法执行任何操作。 有任何想法吗?

如何替换字符串中的字符

我有一个方法,我想用它来替换字符串中的字符: def complexity_level_two replacements = { ‘i’ => ‘eye’, ‘e’ => ‘eei’, ‘a’ => ‘aya’, ‘o’ => ‘oha’} word = “Cocoa!55″ word_arr = word.split(”) results = [] word_arr.each { |char| if replacements[char] != nil results.push(char.to_s.gsub!(replacements[char])) else results.push(char) end } end 我想要的字符串输出应该是: Cohacohaa!55 但是,当我运行此方法时,它不会替换字符,只输出字符串: C o c o a ! 5 5 我在做什么错误,这个方法不会替换字符串中的正确字符以匹配hash中的字符,如何解决这个问题以获得所需的输出?

在Ruby中拆分字符串,忽略括号内容?

我需要在Ruby中将一个字符串拆分成一个部分列表,但是我需要忽略paramentheses中的内容。 例如: A +4, B +6, C (hello, goodbye) +5, D +3 我希望结果列表是: [0]A +4 [1]B +6 [2]C (hello, goodbye) +5 [3]D +3 但我不能简单地用逗号分割,因为这会分割括号的内容。 有没有办法在没有预先解析大括号中的逗号的情况下拆分东西? 谢谢。

字符串破坏性方法似乎不适用于字符串切片

我有一个字符串,我想把第一个字母大写。 我尝试了以下方法: x=’abc’ x[0].upcase! # => “A” x # => “abc” 它不能按预期工作,即使方法是upcase! 是破坏性的。 以下作品: x=’abc’ x[0] = x[0].upcase # => “A” x # => “Abc” 有人可以解释为什么要upcase! 上面不起作用?

用ruby中的数组内容替换字符串?

String = “Test string Test” array = [“link1″,”link2”] 如何替换这样的字符串? 输出应为String = “link1 string link2”

HUGE String上的Ruby String操作

我有一个大小约10 GB的字符串(大量的RAM使用…)。 问题是,我需要执行像gsub和split这样的字符串操作。 我注意到Ruby会在某个时刻“停止工作”(尽管没有产生任何错误)。 例: str = HUGE_STRING_10_GB # I will try to split the string using .split: str.split(“\r\n”) # but Ruby will instead just return an array with # the full unsplitted string itself… # let’s break this down: # each of those attempts doesn’t cause problems and # returns arrays with thousands or […]

字符串由两个不同的分隔符分隔

我有这样的字符串’ some-dasd\dasd-dasdas\dasdas-dasd-das\dsad ‘。 我需要将字符串分成两个不同的符号’\’和’-‘ ,所以我想得到数组[‘some’, ‘dasd’, ‘dasd’, ‘dasdas’, ‘dasdas’, ‘dasd’, ‘das’ ,’dsad’] 。 最好的方法是什么?

为什么从ASCII-8BIT到UTF-8会出现字符串编码问题“\ xE2”?

我正在尝试从电子邮件下载PDF并将内容写入文件。 出于某种原因,我收到此错误: An Encoding::UndefinedConversionError occurred in attachments#inbound: “\xE2” from ASCII-8BIT to UTF-8 app/controllers/api/attachments_controller.rb:70:in `write’ 这是我的代码: def inbound if Rails.env.production? or Rails.env.staging? email = Postmark::Mitt.new(request.body.read) else email = Postmark::Mitt.new(File.binread “#{Rails.root}/app/temp_pdfs/email.json”) end if email.attachments.count == 0 # notify aidin that we got an inbound email with no attachments respond_to do |format| format.json { head :no_content } end […]

如何逃避Ruby中的单引号?

我通过脚本(不是我的)将一些JSON传递给服务器,该脚本接受JSON作为字符串。 JSON的某些内容包含单引号,因此我希望确保在传递给脚本之前对任何单引号进行转义。 我尝试过以下方法: > irb > 1.9.3p194 :001 > x = “that’s an awesome string” > => “that’s an awesome string” > 1.9.3p194 :002 > x.sub(“‘”, “\'”) > => “that’s an awesome string” > 1.9.3p194 :003 > x.sub(“‘”, “\\'”) > => “thats an awesome strings an awesome string” 但似乎无法使语法正确。