在 ruby 我需要一个反斜杠,但它给了我三个
in ruby I need one back slash but it gives me three
我想知道为什么反斜杠 '\' 不能正常工作。
@hash["zebra"] = "African land animal with stripes"
@hash["fish"] = "aquatic animal"
@hash["apple"] = "fruit"
def printable
hashs = @hash
words = Array.new
hashs.each {|key, value|
word = '['+key+'] '+ '\"' + value +'\"\n'
words << word
}
words.sort.join("")
end
我希望
"[苹果]\"fruit\"\n[鱼]\"aquatic animal\"\n[斑马]\"African land animal with stripes\""
但我得到的是
[苹果]\\"fruit\"\n[鱼]\\"aquatic animal\"\n[斑马]\\"African land animal with stripes\"\n
所以它给了我三个反斜杠而不是一个。为什么会这样?
因为有些字符在双引号中时需要转义 "
,这里是它们的一些列表:
\" – 双引号 (")
\ – 单反斜杠 ()
\a – bell/alert(播放音调)
\b – backspace(删除前一个字符,将光标移回一个位置)
\r – carriage return(将光标移动到行首)
\n – 换行符(将光标移动到下一行)
\s – space ( )
\t – 制表符 ( )
在ruby中,单引号里面的内容是一个纯字符串,没有什么特殊作用,所以使用单引号的时候需要改一下内容,或者使用双引号更好的方法是更正确的 ruby 风格
@hash = Hash.new
@hash["zebra"] = "African land animal with stripes"
@hash["fish"] = "aquatic animal"
@hash["apple"] = "fruit"
def printable
hashs = @hash
words = Array.new
hashs.each {|key, value|
word = '['+key+'] '+ '"' + value +'"'+"\n" #use single quote
word = "["+key+"] "+ "\"" + value +"\"\n" #use double quote
words << word
}
words.sort.join("")
puts words
end
我想知道为什么反斜杠 '\' 不能正常工作。
@hash["zebra"] = "African land animal with stripes"
@hash["fish"] = "aquatic animal"
@hash["apple"] = "fruit"
def printable
hashs = @hash
words = Array.new
hashs.each {|key, value|
word = '['+key+'] '+ '\"' + value +'\"\n'
words << word
}
words.sort.join("")
end
我希望 "[苹果]\"fruit\"\n[鱼]\"aquatic animal\"\n[斑马]\"African land animal with stripes\""
但我得到的是 [苹果]\\"fruit\"\n[鱼]\\"aquatic animal\"\n[斑马]\\"African land animal with stripes\"\n
所以它给了我三个反斜杠而不是一个。为什么会这样?
因为有些字符在双引号中时需要转义 "
,这里是它们的一些列表:
\" – 双引号 (")
\ – 单反斜杠 ()
\a – bell/alert(播放音调)
\b – backspace(删除前一个字符,将光标移回一个位置)
\r – carriage return(将光标移动到行首)
\n – 换行符(将光标移动到下一行)
\s – space ( )
\t – 制表符 ( )
在ruby中,单引号里面的内容是一个纯字符串,没有什么特殊作用,所以使用单引号的时候需要改一下内容,或者使用双引号更好的方法是更正确的 ruby 风格
@hash = Hash.new
@hash["zebra"] = "African land animal with stripes"
@hash["fish"] = "aquatic animal"
@hash["apple"] = "fruit"
def printable
hashs = @hash
words = Array.new
hashs.each {|key, value|
word = '['+key+'] '+ '"' + value +'"'+"\n" #use single quote
word = "["+key+"] "+ "\"" + value +"\"\n" #use double quote
words << word
}
words.sort.join("")
puts words
end