Working from a string to an array

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.

···

--
Posted via http://www.ruby-forum.com/.

hi Paul,

  well, i don't know how sexy it is :wink: ...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
  http://www.ruby-doc.org/core-1.9.2/String.html#method-i-gsub

  hth-

  -j

···

--
Posted via http://www.ruby-forum.com/.

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, "!"]

···

--
Posted via http://www.ruby-forum.com/\.

Brian Candler 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.

···

--
Posted via http://www.ruby-forum.com/\.