Modi Ranga Nayakulu
Modi Ranga Nayakulu

Reputation: 369

`+': can't convert String into Array (TypeError)

Hi i am getting an error of

`+': can't convert String into Array (TypeError)

the data in the file is delimited with the TAB.

Data in the file is:

Hi! Welcome to
Hi! Welcome to  google
Hi! Welcome to  google  Technologies
Hi! Welcome to  google  Technologies    Hyderabad 
Hi! Welcome to  google  Technologies    Hyderabad   Telengana
Hi! Welcome to  google  Technologies    Hyderabad   Telengana   India 

read_file=File.open('C:/Users/x/1234567.txt', 'r+')
     read_file.each do |x| 
       #puts x.length   
       array_list=x.split(/\t/)
       #print array_list.length
       case array_list.length
         when 3,4
         puts "hi"
         when 5
         print array_list[0..3]
         when 6
         print array_list[0..3]
         print array_list[0..2] + array_list[4]
         when 7
         print array_list[0..3]
         print array_list[0..2] + array_list[4]
         print array_list[0..2] + array_list[5]
         when 8
         print array_list[0..3]
         print array_list[0..2] + array_list[4]
         print array_list[0..2] + array_list[5]
         print array_list[0..2] + array_list[6]
         else
           puts "Happy"
        end
    end

Upvotes: 2

Views: 698

Answers (1)

Stefan
Stefan

Reputation: 114138

Array#+ concatenates two arrays:

array + other_array

but you're trying to concatenate a string:

array_list[0..2] + array_list[4]

This is because array_list[4] returns a single element.

You can use values_at to fetch multiple indices (or ranges of indices) at once:

array_list.values_at(0..2, 4)

Upvotes: 4

Related Questions