分解-ruby练习中使用的正则表达式的简单解释
问题1 在第一个问题(第2行)中,是否有人可以用Ruby正则表达式新手容易理解的术语来解释正在发生的事情分解-ruby练习中使用的正则表达式的简单解释,ruby,regex,Ruby,Regex,问题1 在第一个问题(第2行)中,是否有人可以用Ruby正则表达式新手容易理解的术语来解释正在发生的事情 def encode(string) string.scan(/(.)(\1*)/).collect do |char, repeat| [1 + repeat.length, char] end.join end def encode(string) string.split( // ).sort.join.gsub(/(.)\1{2,}/) {|s| s.len
def encode(string)
string.scan(/(.)(\1*)/).collect do |char, repeat|
[1 + repeat.length, char]
end.join
end
def encode(string)
string.split( // ).sort.join.gsub(/(.)\1{2,}/) {|s| s.length.to_s + s[0,1] }
end
问题2
在第二个问题中(相同的答案,但解决方案的格式不同)——有人能用Ruby新手容易理解的术语来解释正在发生的事情吗
def encode(string)
string.scan(/(.)(\1*)/).collect do |char, repeat|
[1 + repeat.length, char]
end.join
end
def encode(string)
string.split( // ).sort.join.gsub(/(.)\1{2,}/) {|s| s.length.to_s + s[0,1] }
end
你很容易把它们分解,弄清楚它们在做什么。只需使用IRB、PRY或Sublime Text 2和“眼见为实”插件即可查看每个操作的结果。我将最后一个用于此:
def encode(string)
string # => "foo"
.scan(/(.)(\1*)/) # => [["f", ""], ["o", "o"]]
.collect { |char, repeat|
[
1 + # => 1, 1 <-- these are the results of two passes through the block
repeat.length, # => 1, 2 <-- these are the results of two passes through the block
char # => "f", "o" <-- these are the results of two passes through the block
] # => [1, "f"], [2, "o"] <-- these are the results of two passes through the block
}.join # => "1f2o"
end
encode('foo') # => "1f2o"
如果您不指定您不了解的部分,则很难给出简单的解释。请尝试使用您的编码方法
encode“aaaaaaaaaaaa”或encode“ZYXWWW”
Stack Overflow不是一个“解释其工作原理”网站。相反,您应该尝试使用IRB、Pry或Ruby调试器,并将其分离。试着改变一下,看看会发生什么。至于正则表达式,请通读文档,然后用它来尝试。@YuHao-我在第一个问题中提到了第二行。。。此部分:string.scan(/()(\1*)/),在第二个问题的第二行直到{s | | | | | | |························。我读过文档并做过实验,但让其他人解释是有帮助的。有些人通过这种方式学习得更好@泰曼坦谢谢你!这个插件看起来也很酷。欣赏它非常酷,但目前似乎只适用于Sublime Text 2,否则它将适用于vim。