shin
shin

Reputation: 32721

Using Ruby regex gsub only once

I have the following string.

melody = "F# G# A# B |A# G# F#   |A# B C# D# |C# B A#   |F#   F#   
         |F#   F#   |F#F#G#G#A#A#BB|A# G# F#   "

I want to convert F# to f, G# to g etc.

melody.gsub(/C#/, 'c').gsub(/D#/,'d').gsub(/F#/,'f').gsub(/G#/,'g').gsub(/A#/,'a')

The above gives a desired output. But I am wondering if I can use gsub only once.

"f g a B |a g f   |a B c d |c B a   |f   f   |f   f   |ffggaaBB|a g f   "

Upvotes: 1

Views: 256

Answers (2)

user1375096
user1375096

Reputation:

You can use hash too.

melody.gsub(/[CDFGA]#/, {'C#' => 'c', 'D#' => 'd', 'F#' => 'f', 'G#' => 'g', 'A#' => 'a'})

Upvotes: 1

falsetru
falsetru

Reputation: 369054

String#gsub accepts an optional block: return value of the block is used as replacement string:

melody.gsub(/[CDFGA]#/) { |x| x[0].downcase }
# => "f g a B |a g f   |a B c d |c B a   |f   f   |f   f   |ffggaaBB|a g f   "

Upvotes: 4

Related Questions