Applyng expression to ruby search and replace with regexp
I know in ruby you can search and replace a string using gsub and a
regular expression.
However is there away to apply an expression to the result of the search
and replace before it is replaced.
For example in the code below though you can use the matched string with
\0 you cannot apply expressions to it (eg \0.to_i * 10) and doing so
results in an error:
shopping_list = <<LIST
3 apples
500g flour
1 ham
LIST
new_list = shopping_list.gsub(/\d+/m, \0.to_i * 10)
puts new_list #syntax error, unexpected $undefined
It seems to only work with a string literal:
shopping_list = <<LIST
3 apples
500g flour
1 ham
LIST
new_list = shopping_list.gsub(/\d+/m, '\0 string and replace')
puts new_list
I also tried writing some other convoluted code but couldn't get it to
work which you can see here but will edit out of it is superfluous to the
question. (I was trying to write something that would scale a recipe
originally)
No comments:
Post a Comment