1

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   "

2 Answers 2

4

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   "
Sign up to request clarification or add additional context in comments.

7 Comments

do lowercase conversion..while substituting.
Short and sweet! +1 :)
Can you do this without a block, using a back reference?
@CarySwoveland, No, I can't.
@CarySwoveland Here is the answer, why not possible...
|
1

You can use hash too.

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

2 Comments

I don't think this is the most efficient solution in this case, but it is useful for you to have shown how to do more general substitutions.
yes, it's not short, but more general if your substitution has no relation with the matching.

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.