ReviewApp
def post_review
post = {}
puts "Please enter a genre:"
post[:genre] = gets.chomp
puts "Please enter a title:"
post[:title] = gets.chomp
puts "Please enter your thoughts:"
post[:review] = gets.chomp
line = "---------------------------"
#Drawing a review
puts "Genre: #{post[:genre]}\n#{line}"
puts "title: #{post[:title]}\n#{line}"
puts "Impressions:\n#{post[:review]}\n#{line}"
#Add to array object
posts << post
end
↑ In this case, posts
is not defined in the post_review method
, so it is NG.
In principle, only variables defined in the method can be used.
To be able to use this, we use an argument.
ReviewApp
def post_review (a_posts)
post = {}
puts "Please enter a genre:"
post[:genre] = gets.chomp
puts "Please enter a title:"
post[:title] = gets.chomp
puts "Please enter your thoughts:"
post[:review] = gets.chomp
line = "---------------------------"
#Drawing a review
puts "Genre: #{post[:genre]}\n#{line}"
puts "title: #{post[:title]}\n#{line}"
puts "Impressions:\n#{post[:review]}\n#{line}"
#Add to array object
a_posts << post
# a_returns posts to the method caller
return a_posts
end
#Generate array object posts
posts = []
while true do
#Display menu
puts "Number of reviews: 0"
puts "[0]I write a review"
puts "[1]Read reviews"
puts "[2]Quit the app"
input = gets.to_i
if input == 0 then
posts = post_review(posts) # post_Call review method
elsif input == 1 then
read_reviews # read_Call the reviews method
elsif input == 2 then
end_program # end_Call the program method
else
exception #call the exception method
end
end
The caller should assign this return value to the variable posts. I was able to add review information posts to the array object posts that manage reviews by using arguments.
① Call the post_review method with posts = post_review (posts) with posts as an argument
② In the post_review method, copy posts to a variable called a_posts.
③ Add a hash to a_posts in the post_review method and return a_posts
④ Substitute the returned a_posts for posts by posts = post_review (posts)
Executing a method using arguments
def multi(number) #In the method definition, number is used as a formal argument.
puts number * number
end
puts "Please enter some number"
value = gets.to_i
multi(value) #When actually using the multi method, I put the value instead of the number.
Recommended Posts