ruby 字符串学习笔记1

后端开发   发布日期:2025年06月22日   浏览次数:110

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

  1. hash = { key1: "val1", key2: "val2" }
  2. string = ""
  3. hash.each { |k,v| string << "#{k} is #{v}\n" }
  4. puts string
  5. # key1 is val1
  6. # key2 is val2

变种

  1. string = ""
  2. hash.each { |k,v| string << k.to_s << " is " << v << "\n" }

更高效办法使用 Array#join

  1. puts hash.keys.join("\n") + "\n"
  2. # key1
  3. # key2

或者

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

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

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

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

  1. %{Here is #{class InstantClass
  2.         def bar
  3.           "some text"
  4.         end
  5.  end
  6.        InstantClass.new.bar
  7.  }.}
  8. # => "Here is some text."

here document使用

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

    # => "Dear Mr. Lorum,\nUnfortunately we cannot process your insurance claim at this\ntime. This is because we are a bakery, not an insurance company.\nSigned,\nNil, Null, and None\nBakers to Her Majesty the Singleton\n"
  1. <<end_of_poem
  2. There once was a man from Peru
  3. Whose limericks stopped on line two
  4. end_of_poem
  5. # => "There once was a man from Peru\nWhose limericks stopped on line two\n"

 

以上就是ruby 字符串学习笔记1的详细内容,更多关于ruby 字符串学习笔记1的资料请关注九品源码其它相关文章!