1

An example of the string:

"6 red cables, 4 white cables, 9 blue cables"

I want to remove "cables" so that it reads

"6 red, 4 white, 9 blue"

I looked at the slice and sub methods, but they only remove the first instance of "cables". Can someone point me in the right direction?

2
  • Consider regex? gsub? Commented Apr 12, 2016 at 21:54
  • call gsub("cables", "") on your string. or, more general, make a function like def my_fun(s, x); s.gsub(x, ''); end Commented Apr 12, 2016 at 21:57

2 Answers 2

7

You can use String#gsub:

2.2.0 :003 > "6 red cables, 4 white cables, 9 blue cables".gsub(" cables", "")
 => "6 red, 4 white, 9 blue"
Sign up to request clarification or add additional context in comments.

Comments

-1

Reference (compares sub vs gsub): http://www.dotnetperls.com/sub-ruby

Answer

cleand_value = "6 red cables, 4 white cables, 9 blue cables".gsub("cables", '') 
 Output "6 red , 4 white , 9 blue "

Explanation:

value = "abc abc"
# Gsub replaces all instances.
value = value.gsub("abc", "---")
puts value

Output

--- ---   

You then can get rid of all the white spaces after the commas the same way.

cleaner_value = cleaned_value.gsub(", ", ",") #replaces all instances
output "6 red, 4 white, 9 blue"

Or use the other solutions and do

cleand_value = "6 red cables, 4 white cables, 9 blue cables".gsub(" cables", '') #notice the space before cables. May cause problems unless you know exactly the input

3 Comments

This returns "6 red , 4 white , 9 blue ". To remove those spaces you need to change "cables" to " cables", but then you have @Igor's earlier solution.
Please don't toss out code only. Explain why it's useful and what it does. Handing out code by itself is like throwing someone a fish. Explaining is like teaching them how to fish. The later is better because they'll understand what to do next time.
@theTinMan I edited response. Thanks for the advice, and I like the analogy...seems familiar :D

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.