有没有办法从字符串形式的结构体创建Ruby结构体?

3

我想知道,如果我将结构体转换为字符串(使用 .to_s),是否有办法将其重新转换为结构体?我想知道是否有一些辅助类或其他方法。

我的使用情况是将信息保存在结构体中,然后通过互联网发送,并在另一端从中构建结构体。

提前致谢。


1
将以下与编程有关的内容从英语翻译成中文。仅返回翻译后的文本:请提供一个样例输入和期望输出。原文: "Object-oriented programming (OOP) is a programming paradigm based on the concept of "objects", which can contain data and code: data in the form of fields (often known as attributes or properties), and code, in the form of procedures (often known as methods)."示例输入:无 预期输出:无 - Arup Rakshit
2
最好使用更标准的媒介,比如JSON。编写将你的结构体转换为/自JSON的方法,这样就行了。 - Sergio Tulentsev
@iAmRubuuu 任何你能想象的东西 ;) 只需要一个例子。 - 4rlekin
@SergioTulentsev 看起来很靠谱,我完全忘记了其他选择 :) 谢谢 - 4rlekin
@SergioTulentsev,你能加入这里吗?http://chat.stackoverflow.com/rooms/27184/ruby-conceptual - Arup Rakshit
2个回答

3
为了排除 @Semyon 提供的其他选择,以下是一些解决方案:
  • YAML
    Portable, but rather Ruby specific in its use. Supports serializing any Ruby object in a special way that only Ruby can really understand. If you want portability between Rubies but not languages, YAML is the way to go:

    require 'yaml'
    obj = [1,2,3]
    YAML.dump(obj) #=> Something like "---\n- 1\n- 2\n- 3\n"
    YAML.load(YAML.dump(o)) #=> [1,2,3]
    
  • JSON
    JSON is the most widely recognized and portable data standard for these kinds of things. Portable between Rubies, languages, and systems.

    require 'json'
    obj = [1,2,3]
    obj.to_json #=> "[1,2,3]"
    JSON.load("[1,2,3]") #=> [1,2,3]
    

Marshal 不同的是,这两种方法都是人类可读的。


2

struct.to_s 得到的字符串仅用于检查。要传输结构体,您需要在一侧对其进行序列化,并在另一侧对其进行反序列化。有多种格式可供选择,包括 JSON、YAML 和 Marshal。最后一个格式生成的是非人类可读的字节流,但它是最容易使用的:

Person = Struct.new(:first_name, :last_name)
me = Person.new("Semyon", "Perepelitsa")
p data = Marshal.dump(me)
"\x04\bS:\vPerson\a:\x0Ffirst_nameI\"\vSemyon\x06:\x06ET:\x0Elast_nameI\"\x10Perepelitsa\x06;\aT"

# on the other side
p Marshal.load(data)
#<struct Person first_name="Semyon", last_name="Perepelitsa">

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接