Supposing there’s the following key-value:
hash = {
@bob: 42,
@joe: 1,
@tom: 16,
@luc: 872,
@mike: 32,
...
}
And we would like to transform those string such as:
transform("Hello @bob!")
# => ["Hello ", 42, "!"]
transform("Today @bob and @mike are coding.")
# => ["Today ", 42, " and ", 32, " are coding."]
transform("Hello world.")
# => ["Hello world."]
transform("@tom? TOMCAST! HAHAHA")
# => [16, "? TOMCAST! HAHAHA"]
A method such as this transform() one seems not very hard to implement.
But according to you, want could be the more sexy way to process? With
Ruby 1.9.2 (or 1.9.3).
Thanks.
judge
November 1, 2011, 7:00pm
2
hi Paul,
well, i don’t know how sexy it is …but you could write a
transform
method which splits the String given as its argument (using
#split ,) into an Array. you could then use #gsub ! to replace any
elements of the Array that match keys of the Hash with the value
associated with the key…
gsub(pattern, hash) → new_str
Class: String (Ruby 1.9.2)
hth-
-j
judge
November 1, 2011, 9:01pm
3
Here’s a version which doesn’t split the string into parts:
hash = {
?> “bob”=> 42,
?> “joe”=> 1,
?> “tom”=> 16,
?> “luc”=> 872,
?> “mike”=> 32,
?> }
=> {“mike”=>32, “joe”=>1, “luc”=>872, “tom”=>16, “bob”=>42}
def transform(str, hash)
str.gsub(/@(\w+)/) { hash[$1] }
end
=> nil
transform(“Hello @bob !”, hash)
=> “Hello 42!”
But it’s not much harder to meet your original requirement:
def transform2(str, hash)
str.split(/(@\w+)/).map { |x| x =~ /^@(.+)/ ? hash[$1] : x }
end
=> nil
transform2(“Hello @bob !”, hash)
=> ["Hello ", 42, “!”]
judge
November 1, 2011, 11:42pm
4
Brian C. wrote in post #1029644:
def transform2(str, hash)
str.split(/(@\w+)/).map { |x| x =~ /^@(.+)/ ? hash[$1] : x }
end
=> nil
transform2(“Hello @bob !”, hash)
=> ["Hello ", 42, “!”]
Very cool solution! I didn’t thought about using $1 after split.
Awesome.
Thanks.