思い返すとプログラミングの本ってほとんどがクソだったと思う。
「たのしいRuby」なんてその最たる例だったかも。
Ruby基本
# each
(0..10).each do |i|
puts i
end
# upto
puts "upto!!!"
ary = []
2.upto(10) do |i|
ary << i
end
puts ary
# downto
puts "downto!!!"
ary = []
10.downto(1) do |i|
ary << i
end
puts ary
# arr.each
arr = ["hoge", "fuga", "hogehoge"]
puts arr
arr.each do |a|
puts a
end
# times
5.times do |i|
puts i
end
# for
names = ["taguti","nakazima","fkoji"]
for name in names
puts name
end
# step
puts "step!!!"
ary = []
2.step(10, 3) do |i|
ary << i
end
puts ary # 2, 5, 8
# hash.each
hash = {name: "taguti", age: 30}
hash.each do |k, v|
puts k, v
end
# hash.each
hash = {:name => "taguti", :age => 30}
hash.each do |k, v|
puts k, v
end
# if文
a = "hoge"
if a
puts "ok"
end
# unless
unless a
puts "ok"
end
# loop
#loop do
#print "ruby"
#end
# 例外
names = ["taguti", "fkoji", "yamamoto"]
begin
names.each do |name|
puts name + 10
end
rescue
puts "str in int"
end
#Random
r_int = Random.rand
r_int_100 = Random.rand(100)
puts r_int
puts r_int_100
# split
s = "taguti,fkoji,yamamoto"
s = s.split()
puts s
Rubyファイル操作
# fはFileオブジェクト
File.open("p_test.txt", mode="rt") do |f|
puts f
end
# each_line
File.open("p_test.txt", mode="rt") do |f|
f.each_line do |line|
puts line
end
end
# foreach
File.foreach("p_test.txt") do |line|
puts line
end
puts "\n"
# 読み込んだ行を配列として返す - readlines
s = []
File.open("p_test.txt", mode="rt") do |f|
s = f.readlines
end
p s
puts "\n"
# 書き込み
File.open("ruby_filewrite_test.txt", mode="w") do |f|
f.puts("ruby_filewrite_test.txt")
f.puts("aho")
end
とりあえず each_line と readlines さえ知っとけばいいのかなという感じ。ほかにもあるけどひとつだろっていう。
書き込みは mode=”w” なのはいいとして実際に書き込むときになぜか puts っていう。
正規表現も覚える
sub は 非貪欲マッチ gsub は 貪欲マッチ でrubyは手軽に正規表現が使える。
以下は、ファイルの内容を正規表現で検索して書き換える
puts "regex_before?: "
replace_before = gets.chomp()
puts "regex_aftter?: "
replace_after = gets.chomp()
puts replace_after
content = []
File.open("p_test.txt", "rt") do |f|
content = f.readlines()
end
p content
replace_content = []
content.each do |c|
replace_content.push(c.gsub(/#{replace_before}/, replace_after))
end
p replace_content
# 書き込み
puts "do you really? -- yes or no (y / n) -- "
your_input = gets.chomp()
if your_input == "y"
File.open("p_test.txt", "w") do |f|
replace_content.each do |rc|
f.puts(rc)
end
end
elsif your_input == "n"
end
# 最初に一致したものだけ置換 - 非貪欲マッチ
#content = content.sub(/#{regexp_before}/, regexp_after)
#puts content
# 一致したもの全部置換 - 貪欲マッチ
#content = content.gsub
雑感
別にこれらのrubyに大した意味はないけど、忘れない程度に。忘れていいレベルの知識ではあるけど。

コメント