簡體   English   中英

Ruby printf“%-*。* s”問題

[英]Ruby printf“%-*.*s” problems

我正在嘗試在此處使用以下代碼行:

longest = twoOfArray.inject(0) {|memo,word| memo > word.length ? memo : word.length} longest = twoOfArray.inject(0) {|memo,word| memo > word.length ? memo : word.length}

並將其放入此行的printf中,如下所示:

twoOfArray.each {|k, v| puts "%-*.*s" % [longest] + " " + '*'*v }

但是,它給了我錯誤:

%': too few arguments (ArgumentError)

這是否意味着我的longest變量有問題? 還是我的語法錯誤? 我似乎無法解決問題。 有人在這里看到什么問題嗎?

格式字符串"%-*.*s" expects three arguments: two numbers (one for each *`一個)和一個字符串。 您的數組僅包含一個參數。

hash = {"it"=>3, "was"=>3, "the"=>3, "of"=>2, "times"=>2}

words_array = hash.keys
longest_word = words_array.max_by {|word| word.length}
max_len = longest_word.size

words_array.each do |word|
  number = hash[word]
  str = "#{'*' * (max_len - number)}#{word}#{'*' * number}"
  puts str
end

--output:--
**it***
**was***
**the***
***of**
***times**

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM