简体   繁体   English

使用扫描功能红宝石的空数组

[英]Empty array using scan functrion ruby

I'm just getting started in ruby and I have some trouble understanding the scan method: 我刚开始使用ruby,但在理解scan方法时遇到了一些麻烦:

my_string = "0000000001000100"
string_group = my_string.scan('/...../')
puts string_group
puts string_group.class

It displays that I've got an array but the array is empty. 它显示我有一个数组,但该数组为空。 It can't come from my regex because I tested it and tried with another one: 它不能来自我的正则表达式,因为我对其进行了测试并尝试了另一个:

'/[01]{5}/'

Why do I get an empty array? 为什么我得到一个空数组?

Because regexes in Ruby are literal, not strings -- you have single quotes around your regex, so scan is searching for the literal string /...../ rather than matches to the regex /...../ . 由于Ruby中的正则表达式是文字而不是字符串,因此您在regex周围使用单引号,因此scan搜索的是文字字符串/...../而不是与regex /...../匹配。 Try this instead: 尝试以下方法:

my_string = "0000000001000100"
string_group = my_string.scan(/...../)

Which gives this: 这给出了:

["00000", "00001", "00010"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM