Reputation: 51
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"]
Upvotes: 0
Views: 95
Reputation:
I would actually suggest an entirely different approach; HOWEVER, the main problem with your original code is that you're using an inappropriate method right at the start. each
isn't returning a modified array. Try using map
instead. At a minimum, you'll also want to add a line of code to ensure all other elements return unchanged. If you don't, the other elements will be replaced with nil
values. Here's what your code might look like with minimal modifications:
list= ["beam=0", "active=0", "rate=11", "version=4.1", "delay=5"]
list.map do |lists|
if lists.include?("active=0")
lists = "active=1"
elsif list.include?("active=1")
lists = "active=0"
else
lists
end
end
#=> ["beam=0", "active=1", "rate=11", "version=4.1", "delay=5"]
Upvotes: 0
Reputation: 14776
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
Upvotes: 1
Reputation: 1098
You can iterate through the list
and replace the number after active=
like below:
list= ["beam=0", "active=0", "rate=11", "version=4.1", "delay=5"]
list.each_with_index do |item, index|
next unless item.starts_with?('active')
number_with_active = item.split('active=')[1].to_i
list[index] = "active=#{(number_with_active+1)%2}"
end
Upvotes: 0