ruby 例

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby 例相关的知识,希望对你有一定的参考价值。

# write a test for and create a "deserialize" method to load the file and create an instance of song.

require 'pry'

RSpec.configure do |config|
  # Use color in STDOUT
  config.color_enabled = true

  # Use color not only in STDOUT but also in pagers and files
  config.tty = true

  # Use the specified formatter
  config.formatter = :progress # :progress, :html, :textmate
end

#implement a song class and artist class to pass the specs below.
#serialize method should replace spaces in the song title with underscores
#and write to the current working directory

class Song

  attr_accessor :title, :artist

  def serialize
    split_title = self.title.split(" ")
    formatted = "#{split_title.join("_")}.txt"
    output = File.open("#{formatted}", "w+")
    output << "#{self.artist.name} - #{self.title}"
    output.close
  end
  
  def deserialize(file)
    song_info = File.read(file)
    split_info = song_info.split(" - ")
    self.title = split_info.last
    self.artist = Artist.new(split_info.first)
  end
end

class Artist

  attr_accessor :name

  def initialize(name)
    @name = name
  end
  
end

describe Song do
  it "has a title" do
    song = Song.new
    song.title = "Night Moves"
    song.title.should eq("Night Moves")
  end

  it "has an artist" do
    song = Song.new
    song.title = "Night Moves"
    song.artist = Artist.new("Bob Seger")
    song.artist.name.should eq("Bob Seger")
  end

  it "can save a representation of itself to a file" do
    song = Song.new
    song.title = "Night Moves"
    song.artist = Artist.new("Bob Seger")
    song.serialize
    File.read("night_moves.txt").should match /Bob Seger - Night Moves/
  end

  it "can read a representation of itself from a file" do
    song = Song.new
    song.deserialize(File.open("night_moves.txt"))
    song.title.should eq("Night Moves")
    song.artist.name.should eq("Bob Seger")
  end

end

以上是关于ruby 例的主要内容,如果未能解决你的问题,请参考以下文章

ruby 例

ruby 例

ruby 将YAML配置文件反序列化为单例实例

ruby 解答例https://codeiq.jp/magazine/2014/03/6633/

ruby on rails(测试用例指定创建数据库表)

05-单例(Singleton)模式Ruby实现