Home > Blockchain >  Parsing element in a ruby array
Parsing element in a ruby array

Time:11-29

I like to parse string array and update value, what i have for example:

list= ["beam=0", "active=0", "rate=11", "version=4.1", "delay=5"]

in the above list i want to search for "active" and edit its value, like if "active=0" i want to make it "active=1" , and if its "active=1" i want to make it "active=0".

What i am doing is , but its not correct ,, can someone assist in this:

list.each do |lists|
   if lists.include?("active=0")
      lists = "active=1"
   elsif list.include?("active=1")
      lists = "active=0"
   end
end

what i expect in the end if list contains active=0 , than output list = ["beam=0", "active=1", "rate=11", "version=4.1", "delay=5"] and if list contains active=1, then output list = ["beam=0", "active=0", "rate=11", "version=4.1", "delay=5"]

CodePudding user response:

If you can use a hash, it is much more suitable for this task.

If you cannot, then the problem with your code is that you are not updating the original value. You are just updating the variable used in the '#each` iterator.

One way to do what you want is this:

list = ["beam=0", "active=0", "rate=11", "version=4.1", "delay=5"]

# convert to hash
hash = list.to_h { |x| x.split '=' }

# update any hash value
hash['active'] = hash['active'] == '0' ? '1' : '0'

# convert back to array
result = hash.map { |x| x.join '=' }

and, if for some reason, you wish to stay as close as possible to your original code, then you can use map instead of each. I do not recommend the below code for this case, since this is not good coding, but in case you have your reasons and this is for educational purposes only:

list = ["beam=0", "active=0", "rate=11", "version=4.1", "delay=5"]
result = list.map do |item|
  case item
  when 'active=0' then 'active=1'
  when 'active=1' then 'active=0'
  else
    item
  end
end
  • Related