My goal is to let there be x
so that x("? world. what ? you say...", ['hello', 'do'])
returns "hello world. what do you say..."
.
I have something that works, but seems far from the "Ruby way":
def x(str, arr, rep='?')
i = 0
query.gsub(rep) { i+=1; arr[i-1] }
end
Is there a more idiomatic开发者_JAVA百科 way of doing this? (Let me note that speed is the most important factor, of course.)
If you are talking about the ruby way to accomplish the goal of the function, I would just use "%s world" % ['hello']
.
If you are just asking about the implementation, it looks fine to me. If you don't mind destroying the array, you could tighten it up a bit by doing
query.gsub(rep) { arr.shift }
If it is possible in your use-case I would not add the replacement character as a paramater and then use the standard ruby string formatting mechanism to format the string. This gives you much better control of the variables that you want replaced within the string.
def x(string, values, rep='%s')
if rep != '%s'
string.gsub!(rep, '%s')
end
string % values
end
a = %w[hello do 12]
puts x("? world what ? you say ?", a, '?')
puts x("%s world what %s you say %3.2f", a)
puts x("%s world what %s you say %3.2f", a, '%s')
And the output from this is as follows
hello world what do you say 12 hello world what do you say 12.00 hello world what do you say 12.00
You will need to be careful with this as too few arguments will cause exceptions so you may wish to trap exceptions and behave appropriately. Without knowing your use-case it's hard to tell if this is appropriate or not.
Shorter version:
def x(str, *vals) str.gsub('?', '%s') % vals end
puts x("? world what ? you say ?", 'hello', 'do', '12')
puts x("%s world what %s you say %3.2f", 'hello', 'do', '12')
puts x("%s world what %s you say %3.2f", 'hello', 'do', '12')
Output:
hello world what do you say 12
hello world what do you say 12.00
hello world what do you say 12.00
IMO, the most idiomatic and readable way is this:
def x(str, arr, rep='?')
arr.inject(str) {|memo, i| memo.sub(rep, i)}
end
It probably won't have the best possible performance (or it might be very fast — Ruby's speed depends a lot on the specific implementation you're using), but it's very simple. Whether it's appropriate depends on your goal at the moment.
精彩评论