• ruby 字符串学习笔记1


    1 从一种数据结构中构件字符串

    hash = { key1: "val1", key2: "val2" }
    string = ""
    hash.each { |k,v| string << "#{k} is #{v}
    " }
    puts string
    # key1 is val1
    # key2 is val2

    变种

    string = ""
    hash.each { |k,v| string << k.to_s << " is " << v << "
    " }

    更高效办法使用 Array#join

    puts hash.keys.join("
    ") + "
    "
    # key1
    # key2

    或者

    puts hash.keys.join("") 
    
    # key1key2

     2 创建一个包含ruby变量或者表达式的字符串

    number = 5
    "The number is #{number}."# => "The number is 5."
    "The number is #{5}."# => "The number is 5."
    "The number after #{number} is #{number.next}."# => "The number after 5 is 6."
    "The number prior to #{number} is #{number-1}."# => "The number prior to 5 is 4."
    "We're ##{number}!"# => "We're #5!"

    也可以这样使用但不要这么做

    %{Here is #{class InstantClass
            def bar
              "some text"
            end
                end
           InstantClass.new.bar
     }.}
    # => "Here is some text."

    here document使用

    name = "Mr. Lorum"
    email = <<END
    Dear #{name},
    Unfortunately we cannot process your insurance claim at this
    time. This is because we are a bakery, not an insurance company.
    Signed,
    Nil, Null, and None
    Bakers to Her Majesty the Singleton
    END

    # => "Dear Mr. Lorum, Unfortunately we cannot process your insurance claim at this time. This is because we are a bakery, not an insurance company. Signed, Nil, Null, and None Bakers to Her Majesty the Singleton "
    <<end_of_poem
    There once was a man from Peru
    Whose limericks stopped on line two
    end_of_poem
    # => "There once was a man from Peru
    Whose limericks stopped on line two
    "
  • 相关阅读:
    保罗·多兰《设计幸福》阅读笔记
    依梦随忆(她)
    科技与人性的交汇处----人和机器人的边际在哪里?
    luogu 5月月赛 #A
    luogu P3916 图的遍历
    数论基础之组合数&计数问题
    洛谷——P3173 [HAOI2009]巧克力
    洛谷——P1748 H数
    洛谷——P1404 平均数
    POJ2454——Jersey Politics
  • 原文地址:https://www.cnblogs.com/or2-/p/5006902.html
Copyright © 2020-2023  润新知