我目前正试图将一个字符串转换成多个变量.示例字符串:

ryan_string = "RyanOnRails: This is a test"

我将其与这个regexp匹配,共有3组:

ryan_group = ryan_string.scan(/(^.*)(:)(.*)/i)

ryan_group[0][0] (first group) RyanOnRails
ryan_group[0][1] (second group) :
ryan_group[0][2] (third group) This is a test

这看起来很荒谬,感觉我做错了什么.我希望能做这样的事情:

g1, g2, g3 = ryan_string.scan(/(^.*)(:)(.*)/i)

这可能吗?还是有比我现在做的更好的方法?

推荐答案

你不会想要scan美元,因为这没什么意义.可以使用String#match返回MatchData对象,然后调用#captures返回捕获array.大概是这样的:

#!/usr/bin/env ruby

string = "RyanOnRails: This is a test"
one, two, three = string.match(/(^.*)(:)(.*)/i).captures

p one   #=> "RyanOnRails"
p two   #=> ":"
p three #=> " This is a test"

请注意,如果没有找到匹配项,String#match将返回零,因此类似这样的方法可能会更好:

if match = string.match(/(^.*)(:)(.*)/i)
  one, two, three = match.captures
end

虽然scan对这没什么意义.它仍然可以完成任务,您只需要首先展平返回的array.one, two, three = string.scan(/(^.*)(:)(.*)/i).flatten

Ruby相关问答推荐

类似于模块的 attr_accessor 和 attr_reader 的东西?

VS Code Prettier 打破哈希访问

如果嵌套数组为空,如何判断 ruby​​?

配置 SubLime Linter 插件以使用 Ruby 1.9 语法

Rspec:应该是(this or that)

在 MacOS Sierra 上使用 RMagick 2.16 的 ImageMagick 7 找不到 MagickWand.h

Ruby数组each_slice_with_index?

RSpec:每次指定对具有不同参数的方法的多次调用

我不明白Ruby本地范围(local scope)

如何在Ruby中获取终端窗口的宽度

Ruby 和您必须使用 OpenSSL 支持重新编译 Ruby 或更改 Gemfile 中的源代码

require File.expand_path(..., __FILE__) 是最佳实践吗?

如何使用 Ruby 2.3 中引入的 Array#dig 和 Hash#dig?

to_a 和 to_ary 有什么区别?

如何在数组中找到出现次数最多的项目

如何在 Ruby 的 IRB 中启用自动完成

哪个键/值存储最有前途/最稳定?

什么是 Rakefile?

class << self vs self.method with Ruby:什么更好?

如何判断一个类是否已定义?