Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Geting a Typeerror with hashes (No implicit conversion of symbol into integer)

Tags:

ruby

hash

I made a sample script. Here is the sample script I am running:

def array_generator
  signalp_array = Array.new(11){ Array.new(11,0) }
  signalp = Hash.new
  file = File.readlines("./sample.txt")
  file.each_with_index do |line, idx|
    row = line.gsub(/\s+/m, ' ').chomp.split(" ") # split the line into a array based on white space.
    signalp_array[idx][0..row.length - 1] = row # Merge into existing array
  end
  signalp_array.each do |g|
    seq_id = g[0] 
    cut_off = g[4]
    d_value = g[8]
    signalp[seq_id] = [:cut_off => cut_off, :d_value => d_value] 
  end
  return signalp
 end

signalp = array_generator

puts signalp 
signalp.each do |id, neww|
  puts id
  puts neww[ :cut_off]
  puts neww[ :d_value]
end

with which I am getting the following output and error:

isotig00001_f1_3
in `[]': no implicit conversion of Symbol into Integer (TypeError)

Since the puts signalp line gives me the following:

{"isotig00001_f1_3"=>[{:cut_off=>"11", :d_value=>"0.132"}], "isotig00001_f1_5"=>[{:cut_off=>"11", :d_value=>"0.162"}], "isotig00001_f1_7"=>[{:cut_off=>"11", :d_value=>"0.397"}], "isotig00001_f1_8"=>[{:cut_off=>"11", :d_value=>"0.259"}], "isotig00001_f1_9"=>[{:cut_off=>"11", :d_value=>"0.110"}], "isotig00001_f1_10"=>[{:cut_off=>"11", :d_value=>"0.135"}], "isotig00001_f1_11"=>[{:cut_off=>"1", :d_value=>"0.000"}], "isotig00001_f1_12"=>[{:cut_off=>"12", :d_value=>"0.117"}], "isotig00001_f2_0"=>[{:cut_off=>"11", :d_value=>"0.108"}], "isotig00001_f2_1"=>[{:cut_off=>"28", :d_value=>"0.122"}], "isotig00001_f2_3"=>[{:cut_off=>"19", :d_value=>"0.097"}]}

the hash is created properly. However I cannot access the :cut_off and :d_value individually (probably, because they are digits). I tried to_i, to_s methods etc.

  1. Could someone let me know what I am doing wrong?
  2. Any ideas on what to search for or where to learn more on the topic?
like image 582
Ismail Moghul Avatar asked Dec 02 '22 17:12

Ismail Moghul


2 Answers

neww is not a hash, it is an array [{:cut_off=>"11", :d_value=>"0.132"}]. Do

puts neww[0][:cut_off]
puts neww[0][:d_value]
like image 103
sawa Avatar answered Jan 09 '23 11:01

sawa


The values in your neww hash are arrays of hashes, not just bare hashes. You need to index into the array before keying into the hash. That is:

puts neww[0][:cut_off]
like image 26
Chowlett Avatar answered Jan 09 '23 12:01

Chowlett