Isaac Peretz
Isaac Peretz

Reputation: 21

no implicit conversion of String into Integer (TypeError) Why is it happening?

I'm making a code that reads 3 integers, the first integer being the low interval and the second integer being the high interval, the third integer gives the amount of random numbers that will be displayed, I am getting the error

no implicit conversion of String into Integer (TypeError)

Why? I thought it was its Consant type what was giving the problem but it changed it and it still said the same error :

Interval00, Interval01, Interval02 = gets.chomp.split(&:to_i)

puts "#{Interval00} #{Interval01} #{Interval02}"

array = (Interval00...Interval01).to_a.shuffle.take(Interval02)

array.each do |output| puts output end

Upvotes: 2

Views: 1594

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110685

Prior to Ruby v2.6 String#split did not accept an optional block. That changed with v2.6. The last sentence of the v2.6 doc String#split states, "If a block is given, invoke the block with each split substring." The doc also shows that str, the receiver, is returned.

In the code below I have entered the string "1 2 3" in all cases. One might expect the presence of a block to mean that

gets.split { |s| s.to_i }
  #=> "1 2 3\n"

is the same as

gets.split.map { |s| s.to_i }
  #=> [1, 2, 3]

but clearly it is not, and the doc does not claim that it is. If a block is present, split returns its receiver, here "1 2 3\n" and the block merely performs calculations, much like each.

A simple example of how a block could be used is the following.

a = []
gets.split { |s| a << s.to_i }
  #=> "1 2 3\n" 
a #=> [1, 2, 3] 

Upvotes: 1

Jay Dorsey
Jay Dorsey

Reputation: 3662

You need to change your first line to this:

Interval00, Interval01, Interval02 = gets.chomp.split.map(&:to_i)

Also, you probably don't want to use an uppercase I in your variable name

The error is:

no implicit conversion of String into Integer (TypeError)

This indicates you're trying to do something that expects an Integer, but you really have a String. If you inspect Interval00 with a puts, after you chomp, you'll see it's a String, not an Integer.

When you try and take later, you're passing a String, not an Integer. You'll note:

[1, 2, 3].take("2")

Yields the same error. This is different than:

[1, 2, 3].take(2)

The line I suggested is what applies the to_i to your split data by using map

Upvotes: 0

Related Questions