[英]How best to get all the format sequence keys from a string in ruby?
當給定一個字符串,該字符串打算用 hash 的值格式化以寫入字符串時,是否有一種干凈的方法來獲取字符串期望值的所有鍵?
我在有很大自定義空間的情況下將文本放在一起,並且有幾個動態值選項可以插入到文本中。 有些值比其他值更昂貴,所以我希望能夠准備我的 hash 發送到%
以僅包含字符串中需要的值。
理想情況下,我能夠查詢對字符串執行格式設置的系統,但我沒有看到此類接口的任何文檔。 我想要的是這樣的:
"Your request for %{item} is at position %<pos>d".formatting_keys
>>> [:item, :pos]
我希望能夠准備我的 hash 發送到 % 以僅包含字符串中需要的值。
使用按需計算的 object 而不是 Hash。 這將在任何地方都有用。
使用字符串插值來調用方法而不是格式化序列。
class Whatever
def item
@item ||= calculate_item
end
def pos
@pos ||= calculate_pos
end
private
def calculate_item
# do something expensive
end
def calculate_pos
# do something expensive
end
end
obj = Whatever.new
puts "Your request for #{obj.item} is at position #{obj.pos.to_i}"
根據https://stackoverflow.com/a/74728162使用 Ruby 自己的序列解析是理想的,但您也可以自己做:
class String
def format_keys
scan(
/
(?<!%) # don't match escaped sequence starts, e.g. "%%{"
(?:
(?<=%\{) [^\}]+ (?=\}) # contents of %{...}
| # OR
(?<=%\<) [^\>]+ (?=\>) # contents of %<...>
)
/x
)
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.