1

我刚开始学习Ruby。我正在其中创建一个简单的程序,我仍然不确定如何使用它。这是我的代码:

=begin
Filename: GameCompanyPoem.rb
Program Name: Poem Generator
Version 1.0
Created: March 7th, 2013
Purpose: To generate a poem based on key words given by the user
=end
print 'The following program will ask you to input words. Based on the words you input it will generate a poem. Now, please enter a name. '
name = gets.chomp
print 'Please enter a mammal. '
mammal = gets.chomp
print 'Now please enter a colour. '
colour1 = gets.chomp
print 'We are almost done! Please enter a place or location now. '
place = gets.chomp
print 'Now enter a verb. '
verb1 = gets.chomp
print 'And another verb. '
verb2 = gets.chomp
print 'Your poem will now be generated. Press enter to continue.
space = gets.chomp
print 'Someone by the name of ' + name + 'had a little' + mammal + ', little ' + mammal + ', little ' + mammal + ',' + name + 'had a little ' + mammal + 'its fleece was' + colour + 'as snow. It followed her to ' + place + 'one day, ' + place + 'one day, ' + place + 'one day, it made the children ' + verb1 + 'and ' + verb2 + 'to see a ' + mammal + 'at' + place + '."'

当我运行它时,最后一个方法(打印)中的每个空格都有这个错误:

意外的 tIDENTifier,期待 $end

在每个空间,如果我填写它,它就会消失,但它会进入下一个空间

4

2 回答 2

2

包括 Ruby 在内的许多语言中的一个绝妙技巧,称为插值

print "Someone by the name of #{name} had a little #{mammal}, little #{mammal}, little #{mammal}, had a little #{mammal} its fleece was #{colour} as snow. It followed her to #{place} one day, #{place} one day, #{place} one day, it made the children #{verb1} and #{verb2} to see a #{mammal} at #{place}."

嗯,它可能不再押韵了。

还有一点。查找 Ruby 插值以获取详细信息。但基本上 ruby​​ 会遇到 #{something} 它用某事的结果替换它。

print "1 + 2 = #{1 + 2}"将打印

1 + 2 = 3

于 2013-03-07T18:34:31.843 回答
1

尝试:

print 'Your poem will now be generated. Press enter to continue.'
print 'Someone by the name of ' + name + 'had a little' + mammal + ', little ' + mammal + ', little ' + mammal + ',' + name + 'had a little ' + mammal + 'its fleece was' + colour1 + 'as snow. It followed her to ' + place + 'one day, ' + place + 'one day, ' + place + 'one day, it made the children ' + verb1 + 'and ' + verb2 + 'to see a ' + mammal + 'at' + place + '.'
于 2013-03-07T18:20:16.340 回答