http://www.sw.it.aoyama.ac.jp/2011/PB2/lecture3.html
© 2006-11 Martin J. Dürst 青山学院大学
grains.rb)回答例: grains.rb
calculation.txt のファイル名で Moodle
にアップロード (10月7日 (金曜日) 22:00 必着)irb とプログラムの実行irb:
program_name.rb として保存
(program_name
の部分は実際の名前に変更)ruby program_name.rb で実行(string)
文字列は文字の列
書き方: 一重引用符 (single quote) で囲む:
'abcde', 'ABCDE', '1234''ひらがな', 'カタカナ',
'漢字''aB5漢字カナ交じり文''It\'s fun!' ⇒ It's fun!\' (⇒ ')と \\ (⇒ \)
以外全文字はそのまま(double quotes)
\" ⇒ ", \\ ⇒ \\n ⇒ (改行), \t ⇒ (tab),...#{計算} ⇒
計算結果に置き換えられる使用前:
print 'The result of ' print input print ' * 12 is ' puts input * 12
使用後:
puts "The result of #{input} * 12 is #{input * 12}"
\ と ¥ に注意\" (backslash, reverse solidus)
は日本語のシステムでよく"¥" (yen sign)
と見える¥" を頭の中で "\"
に置き換える文字列 +
文字列'Hello' + ' World!' ⇒ Hello
World!文字列 * 整数'Hello' * 3 ⇒ HelloHelloHello3 * 'Hello' ⇒ エラー(method)
演算子でできない操作はメソッドで実行
書き方: レシーバ.メソッド
優先度: 一番高い; 左結合
具体例:
-5.abs ⇒ 5 (絶対値)2.3.ceil ⇒ 3
(整数に繰り上げ)4.7.floor ⇒ 4
(整数に繰り下げ)5.5.round ⇒ 6
(四捨五入)string.length ⇒ 長さ (文字の数)string.reverse ⇒ 文字の逆順string.succ ⇒ 「次」の文字列string = 'heLlO wORld!'
string.capitalize ⇒ Hello
world!string.downcase ⇒ hello
world!string.swapcase ⇒ HElLO
WorLD!string.upcase ⇒ HELLO
WORLD!(A-Z と a-z だけに影響、それ以外の文字には影響なし)
string.lstrip (左側の空白を除去)string.rstrip (右側の空白を除去)string.strip (両側の空白を除去)string.center 整数
(長さを整数まで拡大、中央揃え)string.ljust 整数
(長さを整数まで拡大、左揃え)string.rjust 整数
(長さを整数まで拡大、右揃え)整数は「引数」(parameter) という
二つ目の引数があれば、スペースの代わりに使用
例: "abcde".center 25, '-*-*-' ⇒
'-*-*--*-*-abcde-*-*--*-*-'
string.count 文字列
(文字列にある文字を
string 内に数える)string.delete 文字列
(文字列にある文字を
string から削除)string.squeeze 文字列
(文字列にある文字の繰り返しを消去)string.to_i (string
の先頭にある数字を整数に変換)string.to_f (string
の先頭にある数字を浮動小数点数に変換)例: 'abc'.to_i → 0; '123abc'.to_i
→ 123; '12.78'.to_i → 12
'abc'.to_f → 0.0; '123abc'.to_f→
123.0; '12.78'.to_i → 12.78
gets で一行入力puts getsinput_string = getsprint 'Please input a string with many spaces:
'
input_string = getsプログラムの例: operations.rb
_):is = getsinput_string = gets# から行末まで.rb)ruby
program.rb で実行どんなにうまいプログラマでも間違いはよくする
提出: 10月 14日 (金曜日) 22:00 までに Moodle に投稿
>>>文字列<<<来週 (10月17日) は海外出張のために休講
次の授業は 10月24日 (月)