落書きノート

ふと自分が気になった事を書いてます

Ruby資格技術者問題集

今回はRangeクラス、範囲について勉強しました。

irb(main):001:0> 1..10
=> 1..10
irb(main):002:0> "a".."z"
=> "a".."z"
irb(main):003:0> 1..10
=> 1..10
irb(main):004:0> (1..5).include?(3)
=> true
irb(main):005:0> (1..5).include?(6)
=> false
irb(main):006:0> (1..5) == 3
=> false
irb(main):007:0> (1..5) == 9
=> false
irb(main):008:0> for i in "a".."z"
irb(main):009:1> p i
irb(main):010:1> end
"a"
"b"
"c"
"d"
"e"
"f"
"g"
"h"
"i"
"j"
"k"
"l"
"m"
"n"
"o"
"p"
"q"
"r"
"s"
"t"
"u"
"v"
"w"
"x"
"y"
"z"
=> "a".."z"
irb(main):011:0> a = ["a","b","c","d","e"]
=> ["a", "b", "c", "d", "e"]
irb(main):012:0> p a[2..3]
["c", "d"]
=> ["c", "d"]
irb(main):013:0> p a[2,3]
["c", "d", "e"]
=> ["c", "d", "e"]
irb(main):014:0> p a[2...3]
["c"]
=> ["c"]
irb(main):015:0> a = "abcdef"
=> "abcdef"
irb(main):016:0> p a[1]
"b"
=> "b"
irb(main):017:0> p a[1..2]
"bc"
=> "bc"
irb(main):018:0> p a[1...2]
"b"
=> "b"
irb(main):019:0> case 1
irb(main):020:1> when 1 then
irb(main):021:1* p 1
irb(main):022:1> end
1
=> 1
irb(main):023:0> case "abc"
irb(main):024:1> when "abc"
irb(main):025:1> p 1
irb(main):026:1> when "abc"
irb(main):027:1> p 2
irb(main):028:1> end
1
=> 1
irb(main):029:0> a = 10
=> 10
irb(main):030:0> b = case a
irb(main):031:1> when 1 then
irb(main):032:1* 1
irb(main):033:1> else
irb(main):034:1* 2
irb(main):035:1> end
=> 2
irb(main):036:0> p b
2
=> 2
irb(main):037:0> case 3
irb(main):038:1> when 1,2 then; p 1
irb(main):039:1> when 3,4 then; p 2
irb(main):040:1> else p 3
irb(main):041:1> end
2
=> 2
irb(main):042:0> case 7
irb(main):043:1> when 1...5 then; p 1
irb(main):044:1> when 5..10 then; p 2
irb(main):045:1> end
2
=> 2
irb(main):049:0> i = 0
=> 0
irb(main):050:0> while(0..4) == i do
irb(main):051:1* p i
irb(main):052:1> i += 1
irb(main):053:1> end
=> nil
irb(main):054:0> i = 0
=> 0
irb(main):055:0> while (0..4) === i do
irb(main):056:1* p i
irb(main):057:1> i += 1
irb(main):058:1> end
0
1
2
3
4
=> nil
irb(main):059:0> i = 0
=> 0
irb(main):060:0> until i == 5 do
irb(main):061:1* p i
irb(main):062:1> i += 1
irb(main):063:1> end
0
1
2
3
4
=> nil
irb(main):069:0> i = 0
=> 0
irb(main):070:0> while(0..4) === i do
irb(main):071:1* p i
irb(main):072:1> i += 1
irb(main):073:1> end
0
1
2
3
4
=> nil
irb(main):074:0> i = 0
=> 0
irb(main):075:0> begin
irb(main):076:1* p i
irb(main):077:1> i += 1
irb(main):078:1> end while(1..4) === i
0
1
2
3
4
=> nil
irb(main):079:0> i = 0
=> 0
irb(main):080:0> p i += 1 while(0..4) === i
1
2
3
4
5
=> nil

頭の運動にもなるし、新しい文法の使い方というのも見れました。while(0..4) === iという部分ですが、iが0..4の範囲内に含まれていれば真を返すという動作が気になりました。上記のコードで細かい違いが見て取れます。そういえば、while修飾子というのもあったんですね。話は逆行しますが、"a"..“z"という範囲を指定できることも初めて知りました。面白いですね。