5

I have many strings following a certain pattern:

string = "Hello, @name. You did @thing." # example

Basically, my strings are a description where @word is dynamically. I need to replace each with a value at runtime.

string = "Hello, #{@name}. You did #{@thing}." # Is not an option!

The @word is basically a variable, but I just cannot use the method above. How should I do that?

1
  • Try searching for it - use this: [ruby] replace string hash. The solution can be as simple (one-two inline expressions) or as complex (template library) as desired. Commented Mar 13, 2013 at 19:35

2 Answers 2

14

Instead doing search/replace, you can use Kernel#sprintf method, or its % shorthand. Combined with Hashes, it can come pretty handy:

'Hello, %{who}. You did %{what}' % {:who => 'Sal', :what => 'wrong'}
# => "Hello, Sal. You did wrong" 

The advantage of using Hash instead of Array is that you don't have to worry about the ordering, and you can have the same value inserted on multiple places in the string.

Sign up to request clarification or add additional context in comments.

1 Comment

Wow, I've never known about this! Ruby is still a surprise for me after 5 years! Thanks a lot for this answer!
6

You can format your string with placeholders that can be switched out dynamically using String's % operator.

string = "Hello, %s. You did %s"

puts string % ["Tony", "something awesome"]
puts string % ["Ronald", "nothing"]

#=> 'Hello, Tony. You did something awesome'
#=> 'Hello, Ronald. You did nothing'

Possible use case: Let's say you were writing a script that would be taking the name and action in as parameters.

puts "Hello, %s. You did %s" % ARGV

Assuming 'tony' and 'nothing' were the first two parameters, you would get 'Hello, Tony. You did nothing'.

1 Comment

And this looks way simpler! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.