Вопрос

I wrote some function which replace one value in a string. It take me some time to figure-out it basing on varius docs, but I would like to ask some champions in RUBY about RIGHT WAY, how to code this?

def replace(newValue)
=begin
    [0]: A0000001561234 = 10,10,1,X,0,0,12345,12345
    1.  A0000001561234 =
    2.  10
    3.  10
    4.  1
    5.  X
    6.  0
    7.  0
    8.  12345
    9.  12345
    //source - http://rubular.com/
=end
    Dir.foreach('./') do |item|
        next if item == '.' or item == '..'
        if item =~ /(.*)online(.*)/
            IO.write(item, File.open(item) do |f| f.read.gsub(/^(A000[0-9]{10}.*)([0-9]{2})\,(.*)\,(.*)\,(.*)\,(.*)\,(.*)\,([1-5]*)\,([1-5]*)\n/x, "\\1\\2,\\3,\\4,\\5,\\6,\\7,#{newValue},\\9\n" ) end)
            puts "done"
        end
    end
end
Это было полезно?

Решение

Just readable variant:

f.read.gsub( /^(A000[0-9]{10})\s*=\s*(.*)/ ) do | _ |
    values = $2.split( ',' )
    values[ 6 ] = new_value
    "A000#{$1} = #{values.join( ',' )}"
end

_ means, that the argument is passed, but isn't used in a fucntion or block, please refer to the good code standart. _ shell be used, when the block strongly requires the explicitly declared argument, and other way, for example, in the code above, it is not needed, and could be just omitted. Also for ruby above equal 1.9 you can use the named group argument for a Regexp, so the code could be optimized as follows:

f.read.gsub( /^(?<key>A000[0-9]{10})\s*=\s*(?<valueset>.*)/ ) do
    values = valueset.split( ',' )
    values[ 6 ] = new_value
    "A000#{key} = #{values.join( ',' )}"
end

Другие советы

It looks like you're following a very round-about path to replace the 8th capture in your pattern. Instead, do it directly, without messing around with an overly complex regular expression:

new_value = 'foobar'
str = 'A0000001561234 = 10,10,1,X,0,0,12345,12345'

values = str.split(',') # => ["A0000001561234 = 10", "10", "1", "X", "0", "0", "12345", "12345"]
values[-2] = new_value
values.join(',') # => "A0000001561234 = 10,10,1,X,0,0,foobar,12345"

values[-2] = new_value is a quick way to index from the end of an array and assign to that slot. Then the code only needs to reassemble the comma-delimited string.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top