ruby操做字符串

 
字符串是ruby最大的內建類,對於字符串的操做有75個以上的標準方法,下面介紹些使用頻繁的方法:
1.分割!
例1:有以下文件
/jazz/j00132.mp3    | 3:45|  Fats Waller        | Ain't Misbehavin'
/jazz/j00319.mp3    | 2:58|  Louis Armstrong    |Wonderful world
/bgrass/bg0732.mp3  | 4:09|  Strength in Number | Texas Red
用對字符串的操做實現:
1.每行分割成各個字段;
2.把播放時間從mm:ss轉換成秒;
3.刪除歌曲演唱者名字中的多餘空格
1.分割字段:string#split前面介紹過的方法,對於切割的模式能夠用Regexp來匹配,/\s*\|\s*/傳遞給split,而後分割成字元
class Song
  def initialize(title, name, duration)
    @title=title
    @name=name
    @duration=duration
  end
  attr_reader :title, :name, :duration
end

class SongList
  def initialize
   @songs=Array. new  
  end
  
  def [](index)
     return "#{@songs[index].name} #{@songs[index].title} #{@songs[index].duration}"    #這句不知道能不能有簡單的方法實現?
  end

  
  def append(song)
   @songs.push(song)  
   self
  end
end

f=File.open('test')
songs=SongList. new
f.each do |line|
  file, length, name, title= line.chomp.split(/\s*\|\s*/)
  song=Song. new(name, title, length)
  songs.append(song)
end
puts songs[1]
輸出結果:Wonderful world Louis Armstrong 2:58
這不是跟結果體數組同樣了麼。。
2.有時候在名字保存的時候中間可能加入多餘的空格(大於1個)能夠用string#squeeze!(" ")方法把多個空格擠壓成一個#squeeze是"擠壓的意思"用!方法是改變字符串的方法。下面代碼

#兩個class類
f=File.open('test')
songs=SongList. new
f.each do |line|
  file, length, name, title= line.chomp.split(/\s*\|\s*/)
   name.squeeze!(" ")
  song=Song. new(name, title, length)
  songs.append(song)
end
puts songs[1]
Wonderful world Louis Armstrong 2:58
轉換時間格式:
在得出length之後能夠對length再進行分割,分紅 min和secs方法1:
min, secs=length.split(/:/)
duration=min.to_i*60+secs.to_i
方法2:
min, secs=length.scan(/\d+/)
duration=min.to_i*60+sec.to_i
用string#scan來掃描字符串中知足regexp的字元,這裏regexp=/\d+/表明是數字的字元
輸出結果
Wonderful world Louis Armstrong 178
 重寫一下第一個步驟的代碼:
class Song
  def initialize(format, name, title, duration)
    @format=format
    @name=name
    @title=title
    @duration=duration
  end
  
  attr_accessor :format, :name, :title, :duration
  
end

class SongList
  def initialize
    @songs=Array. new
  end
  
  def append(song)
    @songs.push(song)
    self
  end
  
  def [](index)
    @songs[index]
  end
  
  def length
    @songs.length
  end
end

f=File.open('test')
songs=SongList. new
f.each do |line|
  format, duration, name, title= line.split(/\s*\|\s*/)
  song=Song. new(format, name, title, duration)
  songs.append(song)
end

(0..songs.length-1).each do  |n|
puts   "#{songs[n].format}--#{songs[n].name}--#{songs[n].duration}--#{songs[n].title}"
end
相關文章
相關標籤/搜索