【问题标题】:Ruby: convert string to arrayRuby:将字符串转换为数组
【发布时间】:2018-04-10 12:29:55
【问题描述】:
a = IO.readlines('uniqID.txt')
puts id = a[0]
id = ["Gh089k" , "HG987"] #getting value from txt file 
id.class #String
id.push("GD977")

如何将上面的字符串转换成数组。所以我使用像推这样的方法。这里的 id 是字符串,看起来像一个数组

Error: undefined method `push' for "[\"Gh089k\", \"HG987\"]":String (NoMethodError)

【问题讨论】:

  • 你能检查一下代码示例吗? id 应该有 Array 类型:[23] pry(main)> id = ["Gh089k" , "HG987"] => ["Gh089k", "HG987"] [25] pry(main)> id.class => Array
  • @mrzasa id 类型为字符串。id.class 将字符串作为输出
  • 你能把你的 uniqID.txt 文件的第一行放进去吗?好像是"[\"Gh089k\", \"HG987\"]" 所以当 ruby​​ 读取它时,它只是一个字符串......
  • 请在控制台中运行id = ["Gh089k" , "HG987"]; id.class
  • @mrzasa id = ["Gh089k" , "HG987"];这给出了一个数组类型。但是当我从 txt 读取时,它充当类型字符串

标签: arrays ruby string


【解决方案1】:

它看起来像一个 JSON 字符串。您可以解析 json 字符串以获得所需的结果。

require 'json'
JSON.parse("[\"Gh089k\", \"HG987\"]") # => ["Gh089k", "HG987"]

这里:

id = JSON.parse(a[0])

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 2014-10-16
    • 1970-01-01
    • 1970-01-01
    • 2012-05-18
    • 1970-01-01
    • 2011-12-15
    • 2010-09-06
    • 2010-10-21
    • 2016-01-18
    相关资源
    最近更新 更多