• 动态创建Struct实例


    Pair = Struct.new(:token, :word)
    first_word = Pair.new("direction", "north")
    second_word = Pair.new("verb", "go")
    #定义一个数组,保存这个新建的Struct
    sentence = [first_word, second_word]
    
    p sentence
    # => [#<struct Pair token="direction", word="north">, #<struct Pair token="verb", word="go">]
    p sentence[0]
    # => #<struct Pair token="direction", word="north">
    #直接使用句号操作符来显示Struct中的数据
    p sentence[0].token,sentence[0].word
    # "direction"
    # "north"
    #或者使用symbol的方式来输出,结果相同
    p sentence[0][:token],sentence[0][:word]
    # "direction"
    # "north"
     

    再来一个实例

    # encoding: UTF-8
    # t=Struct.new('person',:name,:age)
    #算是元编程?
    t=Struct.new('Topic',:name,:replies) #Topic一定得是大写,包括类也是一样,强制性的约定
    p t     # => Struct::Topic
    t1=t.new('first',['good','not bad!','nice!'])
    t2=t.new('second',['不错','好','OK'])
    topics=[t1,t2]
    p topics
        #中文使用p来输出的时候显示的是其unicode编码
        # => [#<struct Struct::Topic name="first",     replies=["good", "not bad!", "nice!"]>, 
        #<struct Struct::Topic name="second", replies=["\u4E0D\u9519", "\u597D", "OK"]>]
    p topics[0].name
        # => "first" 正是动态性的体现,只要有name就能显示
    p topics[1].replies
        # => ["\u4E0D\u9519", "\u597D", "OK"]
     
     
  • 相关阅读:
    Python3基础 keyword 查看所有的关键字
    Python3基础 print 格式化输出 %% 输出%
    Python3基础 print 格式化输出 %f %d 保留浮点数的位数 整数的位数不够零来凑
    Python3基础 for-else break、continue跳出循环示例
    Python3基础 global 在函数内部对全局变量进行修改
    Python3基础 continue while循环示例
    Python3基础 def 函数要先定义再调用
    Python3基础 输出逐行递增的小星星
    Python3基础 九九乘法表
    C#调用接口返回json数据中含有双引号 或其他非法字符的解决办法
  • 原文地址:https://www.cnblogs.com/angestudy/p/2750245.html
Copyright © 2020-2023  润新知