在Ruby中的中心文本周围放置一个框

时间:2018-02-05 18:17:34

标签: 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   *
***********

感谢

1 个答案:

答案 0 :(得分:0)

此处,此代码有效:

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给你的提示

相关问题