年末年始、特に検査もなく、何もやることがないので入院生活の無聊を過ごすのは結構工夫が必要だ。
私の場合、元IT業界のエンジニアだったので意外と学ぶことが多いことを思い出した。
IT業界は常に勉強の世界だからだ。
そこでプログラミング言語「Ruby」に再入門することにした
ここからはRubyの基本的なことをメモしておく。
Ruby概要
オブジェクト指向のスクリプト言語
- 日本人が開発
- Ruby on Railsで有名
- ruby-lang.orgにドキュメント
- Unixコマンドの知識が必要
irbコマンド
対話的にrubyが使える
[localhost 17:26:04 ruby]$ irb
Ignoring nokogiri-1.8.2 because its extensions are not built. Try: gem pristine nokogiri --version 1.8.2
irb(main):001:0> p "hello"
"hello"
=> "hello"
irb(main):002:0> exit
1行にたくさんの命令を書く場合は;で区切る
が普段使わない。
hello.rb
print "Hello world!"#終わったあと改行がない
puts "hello" #改行がある
p "helloworld(p)"#データの形式が分かるように表示
実行結果
[localhost 17:29:41 ruby]$ ruby hello.rb
Hello world!hello
"helloworld(p)"
[localhost 17:29:45 ruby]$
コメントアウト
=begin
コメント
=end
データ
rubyのデータはすべてオブジェクト
メソッドはクラスで定義されている
文字列 String class
p "hello world".length #文字列の長さを返す
実行結果
[localhost 17:13:22 ruby]$ ruby string.rb
11
[localhost 17:13:27 ruby]$
数値オブジェクト – Numericクラス
x = 10 #100_000_000
y = 20.5
z = 1/3r # Rational(1,3)
+,-,*,/,% , **(べき乗)
自己代入も可能
x += 5
p x
p y.round #四捨五入
文字列
name = "takeuchi"
x = "hello \nworld \t#{name}" #変数展開,特殊文字が使える
y = 'hello \nworld \t#{name}'
puts x
puts y
puts "hello " + "takeuchi" #文字列の連結
puts "hello " * 5 #5回繰り返す
実行結果
hello
world takeuchi
hello \nworld \t#{name}
hello takeuchi
hello hello hello hello hello
破壊的メソッドと真偽値を返すメソッド
破壊的メソッド
!マークが付いているもの
真偽値を返すメソッド
?マークがついているもの
upcase.rb
s = "takeuchi"
puts s.upcase #TAKEUCHI
puts s #takeuchi
実行結果
[localhost 17:17:05 ruby]$ ruby upcase.rb
TAKEUCHI
takeuchi
[localhost 17:17:10 ruby]$
元データを書き換えるときに!を使う
upcase2.rb
s = "takeuchi"
puts s.upcase!
puts s
実行結果
[localhost 17:19:27 ruby]$ ruby upcase2.rb
TAKEUCHI
TAKEUCHI
[localhost 17:19:31 ruby]$
boolean.rb
s = "hoge"
p s.empty? #false
s = ""
p s.empty? #true
実行結果
[localhost 17:20:36 ruby]$ ruby boolean.rb
false
true
[localhost 17:20:41 ruby]$
配列オブジェクト
array.rb
sales = [5,8,4,"hoge"]
p sales[0]
p sales[3]
実行結果
[localhost 17:21:48 ruby]$ ruby array.rb
5
"hoge"
[localhost 17:21:53 ruby]$
array2.rb
sales = [5,8,4,"hoge"]
sales[1] = 10
#添字の指定方法はいくつかある
#範囲を指定することも可能
p sales[0..2]#0~2まで表示
p sales[0...2]#2未満まで取得
p sales[-1]#一番最後の要素を取得
p sales[1,2] #配列の1番目から2個取
sales = [5,8,4]
sales[0...2] = [1,2]
p sales
sales[1, 0] = [10,11,12]
p sales
p sales.size #要素数
p sales.sort.reverse #小さい順にソートして逆にする
p sales.push(100) #配列の末尾に追加
sales << 100 #配列末尾に追加
sales << 100 << 102 #このように2回連続追加可能
実行結果
[localhost 17:26:02 ruby]$ ruby array2.rb
[5, 10, 4]
[5, 10]
"hoge"
[10, 4]
[1, 2, 4]
[1, 10, 11, 12, 2, 4]
6
[12, 11, 10, 4, 2, 1]
[1, 10, 11, 12, 2, 4, 100]
[localhost 17:26:04 ruby]$
hashObject
key value
sales = {"taguchi"=>200,"takeuchi" => 300}
sales2 = {:taguchi => 200, :takeuchi => 300}#シンボル
p sales[:taguchi]
p sales2[:taguchi]
実行結果
[localhost 17:07:22 ruby]$ ruby hash2.rb
nil
200
[localhost 17:07:31 ruby]$
#ruby 1.9から
sales = { taguchi: 200, fkouji: 400}
p sales.size
p sales.keys #keyを返してくれる
p sales.values #valueを返してくれる
p sales.has_key?(:taguchi)
実行結果
[localhost 17:04:58 ruby]$ ruby hash.rb
2
[:taguchi, :fkouji]
[200, 400]
true
[localhost 17:04:58 ruby]$
オブジェクトの変換
a = 10
b = "5"
p a+b.to_i #整数になおしてれる
p a + b.to_f #実数になおしてくれる
p a.to_s + b #Stringになおしてくれる
実行結果
[localhost 17:00:50 ruby]$ ruby changeObject.rb
15
15.0
"105"
[localhost 17:00:53 ruby]$
#ハッシュと配列を相互変換可能
h = {taguchi: 100, fkouji:200}
p h.to_a #hashを配列に
p h.to_a.to_h#配列をハッシュに
%記法
s = %Q!hello!
s = %Q(hel"lo)
p s
# s = 'hell\"o'
s = %q(hello")
Qは省略可能
a = ["a", "b", "c"]
a = %W(a b c)
文字列が配列の場合ダブルクオーテーションをたくさん使う場合に便利
a =%w(a b c)
条件分岐
if
真
elsif score > 40
偽
end
score = 80
if score > 60
puts "OK!"
elsif score > 40 #else ifだと syntax errorになる
puts "SoSo.."
else
puts "NG!"
end
実行結果
[localhost 16:53:26 ruby]$ ruby ifexample.rb
OK!
[localhost 16:53:30 ruby]$
score = 80;
puts "OK!" if score > 60
こういう書き方もできる。
実行結果
[localhost 16:55:48 ruby]$ ruby ifexample2.rb
OK!
[localhost 16:55:55 ruby]$
真偽値と条件演算
true: それ以外(0,”を含む)
false: false , nil(オブジェクトが存在しない)
if x #trueの省略形
puts “”
end
条件演算子
a = 条件? b:c
b = 10
c = 20
a = b > c ? b:c
puts a
実行結果
[localhost 16:51:47 ruby]$ ruby conditions.rb
20
[localhost 16:51:51 ruby]$
こんなふうにもかける。
b , c = 10, 20 #多重代入
case文
case 比較したいオブジェクト
when 値
処理
when
else
end
signale = "red"
case signal
when "red"
else #デフォルトになる
end
breakが必要ない
#case文の例
signal = "blue"
case signal
when "red"
puts "Stop!"
when "green","blue"
puts "Go!"
when "yellow"
puts "Caution!"
else
puts "Wrong signal"
end
実行結果
[localhost 16:48:37 ruby]$ ruby case.rb
Go!
[localhost 16:48:40 ruby]$
繰り返し処理
times
3.times do |i|
puts "#{i} :hello"
end
実行結果
[localhost 16:46:07 ruby]$ ruby times.rb
0 :hello
1 :hello
2 :hello
[localhost 16:46:10 ruby]$
必ず0から始まる
while文
i = 0
while i < 3 do
puts "#{i}: hello"
i += 1
end
実行結果
[localhost 16:40:44 ruby]$ ruby while.rb
0: hello
1: hello
2: hello
break文
3.times do |i|
if i == 1
break
end
puts "#{i} :hello"
end
実行結果
[localhost 16:41:43 ruby]$ ruby break.rb
0 :hello
[localhost 16:41:49 ruby]$
1でbreak文から抜ける
next文
3.times do |i|
if i == 1
next
end
puts "#{i} :hello"
end
実行結果
[localhost 16:42:54 ruby]$ ruby next.rb
0 :hello
2 :hello
[localhost 16:43:03 ruby]$
1の処理を飛ばす
まとめると
3.times do |i|
puts "#{i}:hello"
end
puts "==========="
puts "===while==="
i = 0
while i < 3 do
puts "#{i}:hello"
i+=1
end
puts "===break==="
i = 0
while i < 3 do
if i == 1
break
end
puts "#{i}:hello"
i+=1
end
puts "===next==="
3.times do |i|
if i == 1
next
end
puts "#{i}:hello"
end
実行結果
[localhost 16:44:41 ruby]$ ruby allroutine.rb
0:hello
1:hello
2:hello
===========
===while===
0:hello
1:hello
2:hello
===break===
0:hello
===next===
0:hello
2:hello
繰り返し処理2
for,each
for i in 0..2 do
puts i
end
実行結果
[localhost 16:35:55 ruby]$ ruby for.rb
0
1
2
配列、ハッシュを使うことが多い
for color in ["red","blue","pink"] do
puts color
end
実行結果
[localhost 16:36:57 ruby]$ ruby forColor.rb
red
blue
pink
eachメソッドの方がいい
["red","blue","pink"].each do |color|
puts color
end
実行結果
[localhost 16:37:49 ruby]$ ruby eachColor.rb
red
blue
pink
{"red"=>200,"blue"=>100,"pink"=>50}.each do |color,price|
puts "#{color}:#{price}"
end
実行結果
[localhost 16:39:00 ruby]$ ruby eachColor2.rb
red:200
blue:100
pink:50
関数的メソッド
def sayHi(name = "Steave")
puts "hello! " + name
end
sayHi("Tom") #メソッドだと解釈される
sayHi()
返り値も持たせることが可能
def sayHi(name = "steve")
s = "Hello! " + name
return s #return 省略可能
end
greet = sayHi()
puts greet
実行結果
[localhost 16:34:38 ruby]$ ruby steave.rb
Hello! steve
def sayHi(name = "steve")
s = "Hello! " + name
return s #return 省略可能
end
greet = sayHi()
puts greet
クラス(オブジェクトの設計図)
class User #クラス名は必ず大文字から
def initialize(name)#必ずつける、コンストラクタみたいなもの
@name = name
end
def sayHi
puts "hello, my name is #{@name}"
end
end
tom = User.new("Tom")
tom.sayHi()
class User
def initialize(name)
@name = name
end
def sayHi
puts "Hello! My name is #{@name}"
end
end
tom = User.new("tom")
bob = User.new("bob")
tom.sayHi()
bob.sayHi()
class User
def initialize(name)
@name = name
end
def sayHi
puts "Hello! My name is #{@name}"
end
end
tom = User.new("tom")
bob = User.new("bob")
tom.sayHi()
bob.sayHi()
クラスメソッド、クラス変数
class User
@@count = 0 ##クラス変数
def initialize(name)
@name = name #インスタンス変数
@@count += 1
end
def sayHi #インスタンスメソッド
puts "Hello! My name is #{@name}"
end
def User.sayHello #クラス・メソッド
puts "hello from User Class (#{@@count} users)"
end
end
tom = User.new("tom")
bob = User.new("bob")
tom.sayHi()
bob.sayHi()
class User
@@count = 0
def initialize(name)
@name = name
@@count += 1
end
def sayHi
puts "Hello! My name is #{@name}."
end
def User.sayHello
puts "Hello! from class method. (#{@@count} users)"
end
end
tom = User.new("tom")
bob = User.new("bob")
User.sayHello()
実行結果
[localhost ruby]$ ruby classsample.rb
Hello! from class method. (2 users)
クラスの継承
class User
@@count = 0
def initialize(name)
@name = name
@@count += 1
end
def sayHi
puts "Hello! My name is #{@name}."
end
def User.sayHello
puts "Hello! from class method. (#{@@count} users)"
end
end
class SuperUser < User
def shout
puts "Hello!!!!!!!from #{@name}"
end
end
tom = User.new("tom")
bob = SuperUser.new("bob")
tom.sayHi()
bob.shout()
User.sayHello()
class User
@@count = 0
def initialize(name)
@name = name
@@count += 1
end
def sayHi
puts "Hello! My name is #{@name}."
end
def User.sayHello
puts "Hello! from class method. (#{@@count} users)"
end
end
class SuperUser < User
def shout
puts "Hello!!!!!!!from #{@name}"
end
end
tom = User.new("tom")
bob = SuperUser.new("bob")
tom.sayHi()
bob.shout()
User.sayHello()
実行結果
[localhost ruby]$ ruby classsample.rb
Hello! My name is tom.
Hello!!!!!!!from bob
Hello! from class method. (2 users)
アクセサ
getter
def name
return @name
end
setter
def setName(newName)
@name = newName
end
attr_accesser :name #getter,setterを自動生成してくれる
attr_reader :name #getter
attr_writer :name #setter
User.rb
class User
attr_accessor :name
@@count = 0
def initialize(name)
@name = name
@@count += 1
end
def sayHi
puts "Hello! My name is #{@name}."
end
def User.sayHello
puts "Hello! from class method. (#{@@count} users)"
end
=begin
def getName
@name
end
=end
end
SuperUser.rb
require './User' # 別にファイルがある場合
class SuperUser < User
def shout
puts "Hello!!!!!!!from #{@name}"
end
end
tom = User.new("tom")
bob = SuperUser.new("bob")
puts bob.name
puts tom.name
tom.sayHi()
bob.shout()
User.sayHello()
実行結果
[user@localhost ruby]$ ruby classsample.rb
bob
tom
Hello! My name is tom.
Hello!!!!!!!from bob
Hello! from class method. (2 users)
Time
t = Time.now
p t.year
p t.month
p t.day
t = Time.new(2013,12,25,12,32,22)
p t
秒数を足すことが可能
p t + 10
p t.strftime("Updated : %Y-%m-%d")
実行結果
[user@localhost ruby]$ ruby time.rb
2015
9
1
2013-12-25 12:32:22 +0900
2013-12-25 12:32:32 +0900
"Updated : 2013-12-25"
[user@localhost ruby]$
以上、Rubyに興味ない人には意味がないかもしれませんがこんな復習を2年ぶりくらいにしました。
コメント