#!/usr/bin/ruby

filename=ARGV[1]
text=File.readlines(filename)
text.each_with_index do |line,i|
if line =~ /#{ARGV[0]}/
print "#{i+1}: #{line}"
end
end

1.
#!/usr/bin/ruby
class Counter
  def initialize
    @count=0
  end

  def count
    @count
  end

  def setCount(num=0)
    @count=num
  end

  def getCount
    puts @count
  end

  def increase
    @count+=1
  end

  def decrease
    @count-=1
    if @count<=0
      @count=0
    end
  end
end

oita=Counter.new
oita.setCount(10)
oita.getCount
oita.increase
oita.getCount
oita.increase
oita.getCount

実行結果
10
11
12

2.
#!/usr/bin/ruby

require "07-1"
class NewCounter < Counter
  def increase(num=1)
    @count+=num
  end

  def decrease(num=1)
    @count-=num
    if @count<=0
      @count=0
    end
  end

  def time(num)
    @count*=num
  end

  def div(num)
    @count/=num
  end
end

oita=NewCounter.new
oita.setCount(100)
oita.getCount
oita.time(3)
oita.getCount
oita.div(2)
oita.getCount

実行結果
10
11
12
100
300

#!/usr/bin/ruby

puts "変換したい曜日の入力"
def wday
date = {"sunday" => "日曜日",
"monday" => "月曜日",
"tuesday" => "火曜日",
"wednesday" => "水曜日",
"thursday" => "木曜日",
"friday" => "金曜日",
"saturday" => "土曜日"}
puts date[$day]
end

$day = gets.chomp

wday

実行結果
変換したい曜日の入力
monday
月曜日

1.行列式の計算
#!/bin/usr/ruby -wKu
a=[1,2,3]
b=[4,5,6]

a.length.times{|i|
p a[i]+b[i]
}

実行結果
5
7
9

2.文字,文字列,数字が混じったaryをsortする
#!/bin/usr/ruby -wKu
a=[-100.to_s,"hoge",'a',1.to_s]
p a.sort

実行結果
["-100", "1", "a", "hoge"]

3.reverseを使わずreverseを実装
#!/usr/bin/ruby -wKu
a="hogefuga".split(//)
b=a.size
b.times {|b|
c=[]
c=a.pop

print c
}
puts

実行結果
agufegoh

1.文字列のbit数の表示プログラム
#!/bin/usr/ruby -wKu

puts "バイト数をしりたい文字列の入力"
a = gets.chomp

puts "バイト数は"
puts a .length

実行結果
t07057@t07057pc:~/Desktop/ruby課題$ ruby 04-1.rb
バイト数をしりたい文字列の入力
あああああ
バイト数は
15

2.文字列を変化させて表示させるプログラム
#!/bin/usr/ruby -wKu
puts "変化させる文字の入力"
a = gets.chomp
puts a+a.reverse
b = a.reverse.capitalize.reverse
puts b+a.reverse.capitalize

実行結果
t07057@t07057pc:~/Desktop/ruby課題$ ruby 04-2.rb
変化させる文字の入力
abc
abccba
abCCba

四則演算

#!/bin/usr/ruby

puts "ひとつめの数の入力"
a = gets.chomp

puts "四則演算子の入力"
b = gets.chomp

puts "ふたつめの数の入力"
c = gets.chomp

case b

when "+"
puts a.to_i + c.to_i
when "-"
puts a.to_i - c.to_i
when "*"
puts a.to_i * c.to_i
when "/"
puts a.to_i / c.to_i
end

実行結果
t07057@t07057pc:~/Desktop$ ruby 03-1.rb
ひとつめの数の入力
5
四則演算子の入力
*
ふたつめの数の入力
3
15

・1000回サイコロを振った出目の平均

#!/usr/bin/ruby

n = 0
1000.times do |i|
sai = rand(6) + 1
n += sai
end
puts "1000回サイコロを振った出めの平均は#{n/1000}"

実行結果

1000回サイコロを振った出めの平均は3

・headコマンドの作成

#!/usr/bin/ruby

line = 0
while true
input = gets
break if input == nil
line += 1
print "#{line}: #{input.chomp}\n"
end

実行結果

$ ruby 0001.rb

このブログ記事は、Movable Type 4のインストール完了時に、システムによって自動的に作成されたブログ記事です。 新しくなったMT4の管理画面で、早速ブログを更新してみましょう。