0.1から始めるプログラミング 開発のほう ruby アプリ1

# -*- coding: utf-8 -*-
class SongInfo
  #初期化
  def initialize(name, singer, music, words )
    @name = name
    @singer = singer
    @music = music
    @words = words
  end

  #アクセサ
  attr_accessor :name, :singer, :music, :words

  #文字列表現
  def to_s
    "#@name,#@singer,#@music,#@words"
  end

  #csv表現
  def to_csv( key )
    "#{@name},#{@singer},#{@music},#{@words}\n"
  end

  #書式を指定して出力 引数は区切り文字 省略した場合は改行
  def toFormattedString(seq = "\n")
    "曲名: #{@name}#{seq}歌手: #{@singer}#{seq}作曲: #{@music}#{seq}作詞: #{@words}#{seq}"
  end
end

#管理用のManagerクラスを定義
class SongInfoManager
  def initialize( filename )
    @csv_fname = filename
    @song_infos = {}
  end

  def setUp
    open(@csv_fname, "r:UTF-8") {|file|
      file.each {|line|
        key, name, singer, music, words = line.chomp.split(',')
        @song_infos[ key ] = SongInfo.new(name, singer, music, words)
      }
    }
  end

  def addSongInfo
    song_info = SongInfo.new("","","","")
    print "\n"
    print "key: "
    key = gets.chomp
    print "曲名: "
    song_info.name = gets.chomp
    print "歌手: "
    song_info.singer = gets.chomp
    print "作曲: "
    song_info.music = gets.chomp
    print "作詞: "
    song_info.words = gets.chomp
    
    @song_infos[key] = song_info
  end
  
  def saveAllSongInfos
    open(@csv_fname, "w:UTF-8") {|file|
      @song_infos.each {|key,info|
        file.print (info.to_csv ( key ))
      }
      puts "\nファイルを保存しました"
    }
  end



  def listAllSongInfos
    puts "\n--------------------"
    @song_infos.each{|key, info|
      print info.toFormattedString
      puts "\n-------------------"
    }
  end

def run
  while true
    print "
1.曲データの登録
2.曲データの表示
8.曲データをファイルに保存
9.終了
番号を選んでください(1 or 2 or 9) :"

    num = gets.chomp
    case 
      when '1' == num
      addSongInfo

      when '2' == num
      listAllSongInfos

      when '8' == num
      saveAllSongInfos
      
      when '9' == num
      break;

      else
      #選択待ち画面に戻る
      end
  end
end
end

song_info_manager = SongInfoManager.new("song_info.csv")

song_info_manager.setUp

song_info_manager.run

結局本に書いてあったコードを写してるから、ここで見直しながらもう一度仕様を確認しようと思う。現時点では起動するとメニュー画面(CUI)が出て、

・曲データをキャッシュのハッシュに保存する
・ハッシュに保存されてる曲データの表示
・ハッシュのデータをcsv形式で予め指定されているファイルに保存
・アプリケーションの終了

を選択することになっている。
次章からはデータ管理にデータベース(SQLite)をするらしい。なんとなく本格的な香りが漂うので楽しみだけど、まずrubyからsqliteを扱うライブラリの導入が少し詰まって、危なかった
このアプリケーションを育てながら、色々学んでいきたいと思う。本から抜けだして本格的に自分のアイデアをコードに移す段階になったら、またこっちに載せてきたい。()