简体   繁体   中英

Empty array using scan functrion ruby

I'm just getting started in ruby and I have some trouble understanding the scan method:

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 /...../ . Try this instead:

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

Which gives this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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