0

I am trying to find if there is mango/cc: in my data and if its there update its value to new_version, if its not there add mango/cc:#{new_version}

My data

{"product"=>"fruit", "id"=>"alpha", "details"=>{"SS"=>["mango/aa:50", "mango/cc:287_457_51.0.0"]}}

Code:

  new_version = "287_457_53.0.0"
  var1 = data['details']['SS'].select{|x| x.start_with?('mango/cc:')}
  if var1.empty?
    data['details'] << "mango/cc:#{new_version}"
  else
    data['details'].delete(var1)
    data['details'] << "mango/cc:#{new_version}"
    puts data

Current Output:

`[]': no implicit conversion of String into Integer (TypeError)

Expected Output:

{"product"=>"fruit", "id"=>"alpha", "details"=>{"SS"=>["mango/aa:50", "mango/cc:287_457_53.0.0"]}}
1
  • I don't get the same error with this code. Are you sure you posted corrrectly? Commented Mar 6, 2020 at 16:05

2 Answers 2

1

So it should work:

data={"product"=>"fruit", "id"=>"alpha", "details"=>{"SS"=>["mango/aa:50", "mango/cc:287_457_51.0.0"]}}
puts "Before: #{data}"
new_version = "287_457_53.0.0"
var1 = data['details']['SS'].select{|x| x.start_with?('mango/cc:')}
if var1.empty?
  data['details']['SS'] << "mango/cc:#{new_version}"
else
  data['details']['SS'].delete(var1.first)
  data['details']['SS'] << "mango/cc:#{new_version}"
end
puts "After: #{data}"

#=> Before: {"product"=>"fruit", "id"=>"alpha", "details"=>{"SS"=>["mango/aa:50", "mango/cc:287_457_51.0.0"]}}
#=> After: {"product"=>"fruit", "id"=>"alpha", "details"=>{"SS"=>["mango/aa:50", "mango/cc:287_457_53.0.0"]}}

There are several errors:

 var1 is an array
 data ['details'] is hash table
 "mango / cc: # {new_version}" is a string

You should add ['SS'] to delete the key (string) "mango / cc: # {new_version}" remembering that var1 is an array and not a string

Sign up to request clarification or add additional context in comments.

Comments

0

I think that the error is because var1 is an array, so your code must be something like:

new_version = "287_457_53.0.0" 
var1 = data['details']['SS'].select{|x| x.start_with?('mango/cc:')}
if var1.empty?
  data['details'] << "mango/cc:#{new_version}"
else
  data['details'].delete(var1.first)
  data['details'] << "mango/cc:#{new_version}"
  puts data

Just changing the param in data['details'].delete method

Comments

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.