FORMATING CHARACTER STRING WITH ASSOCIATIVE ARRAY IN Ruby

Asked 2 years ago, Updated 2 years ago, 30 views

I would like to do the following (some_method).

some_method "aa/:foo/:bar/bb", {foo:1,bar:2}
>aa/1/2/bb

The following text
Title: How to format string by hash variable on ruby?

I wanna do it.

some_method "aa/:foo/:bar/bb", {foo:1,bar:2}
>aa/1/2/bb

ruby

2022-09-30 17:02

3 Answers

If you want to use a hash, and you want to format it in any format,

'aa/%<foo>s/%<bar>s/bb'% {foo:1,bar:2}

Or

sprintf'aa/%<foo>s/%<bar>s/bb',foo:1,bar:2

I wonder if that'sorry. Because it is part of Ruby's printf format specification, you can specify the number of digits in the number as well as printf.


2022-09-30 17:02

Miscellaneous.

require 'mustermann'

def some_method(fmt,h)
  Mustermann.new(fmt).expand(h)
end


2022-09-30 17:02

'aaa/:foo/:bar/bb'.gsub(/:(\w+)/){{foo:1,bar:2}.fetch($~[1].to_sym)}


2022-09-30 17:02

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.