这是一个 super 基础的 ruby 问题。刚刚学习 ruby,我正在尝试构建一个框,它可以在其中找到字符串中最长的单词,并使该框的宽度在两边都有空格,然后将我传入的所有其他文本居中。
到目前为止我有这个;
def box(str)
arr = str.split
wordlength = arr.max_by(&:length).length
width = wordlength + 4
width.times{print "*"}
puts "\n"
arr.each {|i| puts "* #{i} *" }
width.times{print "*"}
end
但是上面的打印出来了:
***********
* texting *
* stuff *
* test *
* text *
***********
我希望它打印出类似下面的内容
***********
* texting *
* stuff *
* test *
* text *
***********
谢谢
最佳答案
在这里,这段代码有效:
def box(str)
arr = str.split
wordlength = arr.max_by(&:length).length
width = wordlength + 4
width.times{print "*"}
puts "\n"
arr.each do |i|
current_length = i.length
puts "* #{fill_space(current_length, wordlength, 'pre', i)}#{i}#{fill_space(current_length, wordlength, 'post')} *"
end
width.times{print "*"}
end
def fill_space(current_length, max_length, where, current='')
spaces_to_fill = max_length - current_length
if where == 'pre'
str = ' ' * (spaces_to_fill / 2)
elsif spaces_to_fill % 2 > 0
str = ' ' * (spaces_to_fill / 2 + 1)
else
str = ' ' * (spaces_to_fill / 2)
end
end
问题是,您没有计算应该在当前行中插入多少个 ""。在 fill_space 函数中,我准确地计算了这一点,并为应该打印的每一行调用了这个函数。此外,如果有奇数词,此函数会在行尾添加额外的空格。
我没有对你的盒子函数做太多改动,但可以随意插入 Keith 给你的提示
关于ruby - 在 Ruby 中围绕居中文本放置一个框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48628947/