ZirconCode
ZirconCode

Reputation: 817

How can I DRY out this Ruby Code

How can I DRY out the following Ruby Code:

    x = 'a random string to be formated'
    x = x.split('^')[0] if x.include?('^')
    x = x.split('$')[0] if x.include?('$')
    x = x.split('*')[0] if x.include?('*')

I'm looking for the amazingly elegant ruby one liner but I'm having a hard time finding it. It should probably be somewhat readable though.

Thanks

Upvotes: 1

Views: 121

Answers (4)

000
000

Reputation: 27247

You're looking for this regex:

string.match(/^([^^$*]+)[$^*]?/).captures[0]

It returns all characters up the the first occasion of $, ^, or *, or the end of the string.

Upvotes: 0

thank_you
thank_you

Reputation: 11107

Based on the code you provided

x = 'a random string to be formated'

%w(^ $ *).each do |symbol|
  x = x.split(symbol)[0] if x.include?(symbol)
end

Upvotes: 0

user1898811
user1898811

Reputation:

This works for me:

x = "a random string to be formatted"
['^', '$', '*'].each { |token|
  x = x.split(token)[0] if x.include?(token)
}

Upvotes: 0

teubanks
teubanks

Reputation: 710

I think this might be what you're looking for

x.split(/\^|\$|\*/)

Upvotes: 2

Related Questions