我正在进行编码训练营,进入第2周,并且学习了循环,方法和一些类。我遇到了这种编码挑战。
我可以在def方法中的句子周围加上一个框。我想知道如何围绕用户输入的单词添加一个框架。我已经尝试过,但是出现错误。
最终,我要实现的是从def方法中删除words = %w(This restaurant has an excellent menu - sushi ramen okonomiyaki.)
。
谢谢!
puts "Welcome to frame with words."
puts "Enter your favourite quote or sentence or any word you like"
words = gets.chomp.to_s
def my_favourite words=[]
words = %w(This restaurant has an excellent menu - sushi ramen okonomiyaki.)
longest = 0
words.each {|word| longest = word.length if longest < word.length }
(0..longest+3).each {print "*"}
print "\n"
words.each do |word|
print "* "
print word
(0..longest-word.length).each { print " " }
print"*\n"
end
(0..longest+3).each {print"*" }
return
end
my_favourite
我想要的输出类型如下。
* This *
* restaurant *
* has *
* an *
* excellent *
* menu *
* - *
* sushi *
* ramen *
* okonomiyaki. *
**************** ```
假设
str = gets.chomp
#=> "This restaurant has an excellent menu - sushi ramen."
然后
words = str.split
#=> ["This", "restaurant", "has", "an", "excellent", "menu", "-",
# "sushi", "ramen."]
width = words.max_by(&:size).size
#=> 10
top_bot = '*' * (width+4)
#=> "**************"
puts top_bot
words.each { |word| puts "* %-#{width}s *" % word }
puts top_bot
显示:
**************
* This *
* restaurant *
* has *
* an *
* excellent *
* menu *
* - *
* sushi *
* ramen. *
**************
words.max_by(&:size)
的简称:
words.max_by { |word| word.size }
#=> "restaurant"
请参阅文档Kernel#sprint,以获取"* %-#{width}s *" % word
中格式代码的说明。替换为#{width}
后,该名称将变为"* %-10s *" % word
。 s
指定word
是字符串。 10
表示它应该占据宽度10
的字段。 -
表示该字符串应在字段中向左调整。宽度为10
的字段之前是"* "
,然后是" *"
,形成了宽度为14
的字符串。
这可以(等效地)写成:
word = "balloon"
sprintf("* %-#{width}s *", word)
#=> "* balloon *"
假设
str = gets.chomp
#=> "This restaurant has an excellent menu - sushi ramen."
然后
words = str.split
#=> ["This", "restaurant", "has", "an", "excellent", "menu", "-",
# "sushi", "ramen."]
width = words.max_by(&:size).size
#=> 10
top_bot = '*'*(width+4)
#=> "**************"
puts top_bot
words.map { |word| puts "* %-#{width}s *" % word }
puts top_bot
显示:
**************
* This *
* restaurant *
* has *
* an *
* excellent *
* menu *
* - *
* sushi *
* ramen. *
**************
words.max_by(&:size)
的简称:
words.max_by { |word| word.size }
#=> "restaurant"