Ruby 入門 -6ページ目

Ruby 入門

~ Ruby初心者による逆引き備忘録 ~

<< 目次

ファイルを判定する。

path = "./file.txt"
if File::ftype(path) == "file"
puts "#{path} is file"
end



ディレクトリを判定する。

path = "./DIR"
if File::ftype(path) == "directory"
puts "#{path} is directory"
end


<< 目次
<< 目次

dir の中の file 一覧を取得する。

path = "./"
p Dir::entries(path)


しかし "." とか ".." とかもファイルとして判断されてしまうのでさらに以下を行うと便利。

dir = "./"
files = Dir::entries(dir)
files.each{|file|
path = "#{dir}/#{file}"
if File::ftype(path) == "file"
puts "#{path} is file"
end
}


<< 目次
<< 目次

filename から line で読み込んで都度表示する。

open(filename){|f|
f.each{|line|
puts line
}
}


path の file を から readlines で読み込んで配列 array に格納する。

def read_file path
array = []
open(path){|f|
array = f.readlines
}
return array
end


<< 目次
<< 目次

require は、必須です。


require 'date'

# today
today = DateTime.now.strftime('%Y-%m-%d')
puts today

# yesterday
yesterday = (DateTime.now - 1).strftime('%Y-%m-%d')
puts yesterday

# 1 month ago
monthago = (DateTime.now << 1).strftime('%Y-%m-%d')
puts monthago

# 3 month ago
threemonthago = (DateTime.now << 3).strftime('%Y-%m-%d')
puts threemonthago



<< 目次
<< 目次

※ Time は、時間の制限があるので推奨ではないらしい。使うなら Date らしい。

現在時刻を取得する。

time = Time.now
year = time.year
month = time.month
day = time.day

2009/01/01 とか 0 を入れたい場合 strftime を使う。

time = Time.now
yyyy = time.strftime("%Y")
mm = time.strftime("%m")
dd = time.strftime("%d")


<< 目次