配列オブジェクトpostsを引数として渡す
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
# メソッドの定義
def post_review(a_posts)
# 変数の定義
post = {}
puts "ジャンルを入力してください:"
post[:genre] = gets.chomp
puts "タイトルを入力してください:"
post[:title] = gets.chomp
puts "感想を入力してください:"
post[:review] = gets.chomp
line = "---------------------------"
# レビューの描画
puts "ジャンル : #{post[:genre]}\n#{line}"
puts "タイトル : #{post[:title]}\n#{line}"
puts "感想 :\n#{post[:review]}\n#{line}"
# 配列オブジェクトに追加
a_posts << post
# a_postsをメソッドの呼び出し元に返す
return a_posts
end
def read_reviews
# レビューを読む
end
def end_program
exit
end
def exception
puts "入力された値は無効な値です"
end
posts = [] # 配列オブジェクトpostsの生成
while true do
# メニューの表示
puts "レビュー数:0"
puts "[0]レビューを書く"
puts "[1]レビューを読む"
puts "[2]アプリを終了する"
input = gets.to_i
if input == 0 then
posts = post_review(posts) # post_reviewメソッドの呼び出し
elsif input == 1 then
read_reviews # read_reviewsメソッドの呼び出し
elsif input == 2 then
end_program # end_programメソッドの呼び出し
else
exception # exceptionメソッドの呼び出し
end
end
|
レビューを管理する配列オブジェクトpostsはメソッドpost_reviewの外で定義されているので、そのままではpost_review内で使うことはできない。そこで、post_reviewメソッドにはpostsを引数として渡す。
メソッドの呼び出し側では、postsを渡すようにする。
47 48 |
if input == 0 then
posts = post_review(posts) # post_reviewメソッドの呼び出し
|
そしてpost_reviewメソッドでは引数postsをa_posts
という変数にコピーして使う。
2 |
def post_review(a_posts)
|
これで、post_reviewメソッド内でレビューを管理する配列オブジェクトpostsはa_posts
という変数で使用することが可能となる。メソッドの最後でレビューの情報であるハッシュオブジェクトpostをa_posts
に追加する。追加は<<メソッド。
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
def post_review(a_posts)
# 変数の定義
post = {}
puts "ジャンルを入力してください:"
post[:genre] = gets.chomp
puts "タイトルを入力してください:"
post[:title] = gets.chomp
puts "感想を入力してください:"
post[:review] = gets.chomp
line = "---------------------------"
# レビューの描画
puts "ジャンル : #{post[:genre]}\n#{line}"
puts "タイトル : #{post[:title]}\n#{line}"
puts "感想 :\n#{post[:review]}\n#{line}"
# 配列オブジェクトに追加
a_posts << post
end
|
もともと、a_postsはpostsがコピーされたもの。以上よりa_postsにpostハッシュが新たに追加されたが、コピー元であるpostsは更新されない。
そこで、a_postsを返り値として返し、postsに代入する。
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
def post_review(a_posts)
# 変数の定義
post = {}
puts "ジャンルを入力してください:"
post[:genre] = gets.chomp
puts "タイトルを入力してください:"
post[:title] = gets.chomp
puts "感想を入力してください:"
post[:review] = gets.chomp
line = "---------------------------"
# レビューの描画
puts "ジャンル : #{post[:genre]}\n#{line}"
puts "タイトル : #{post[:title]}\n#{line}"
puts "感想 :\n#{post[:review]}\n#{line}"
# 配列オブジェクトに追加
a_posts << post
# a_postsをメソッドの呼び出し元に返す
return a_posts
end
|
以上により、post_review内で使われていた変数a_postsをメソッドの呼び出し元に返す。
呼び出し元ではこの返り値を変数posts
に代入するようにする。
47 48 |
if input == 0 then
posts = post_review(posts) # post_reviewメソッドの返り値(a_posts)をpostsに代入
|
引数を使うことでレビューを管理する配列オブジェクトpostsにレビューの情報postを追加できた。
① posts = post_review(posts)でpost_reviewメソッドを、postsを引数として呼び出す
② post_reviewでは、postsをa_postsという変数にコピーする
③ post_reviewでa_postsにハッシュを追加し、a_postsを返す
④ posts = post_review(posts)により、返されたa_postsをpostsに代入する