Forum: Ruby Implicit Conversion

F76622565610f5c990a3c7ab544e3546?d=identicon&s=25 Demetirck Demetrickn (demetrickn)
on 2008-11-19 21:39
Hello all,
I'm new to this site I'm an intern at software company and was given the
task of writing a program in ruby that simply could open data files
check for a particular field in the text file and compare the intger
agains't a mininum value.

I seem to be getting a prblem from ruby that says
" `[]': no implicit conversion from nil to integer (TypeError)"

Ruby doesn't seem to let me give integer values to an array inside a
loop.
Is there anyway I can  static cast or do a type conversion in ruby ?
7a561ec0875fcbbe3066ea8fe288ec77?d=identicon&s=25 Sebastian Hungerecker (Guest)
on 2008-11-19 21:47
(Received via mailing list)
Demetirck Demetrickn wrote:
> I seem to be getting a prblem from ruby that says
> " `[]': no implicit conversion from nil to integer (TypeError)"
>
> Ruby doesn't seem to let me give integer values to an array inside a
> loop.

That error doesn't happen when you give an integer, it happens when you
give
nil. array[1] works, array[nil] does not. So likely you have a variable
that
is nil or a method that returns nil, while you expect it to return an
integer.
(For example Regex#=~ returns nil if the regex does not match. So if you
use
the return value from =~, you'll have to check that it's not nil before
using
it in []).

HTH,
Sebastian
Edfcfb783260609029d57cd4e1c39d65?d=identicon&s=25 Alan Johnson (Guest)
on 2008-11-19 21:51
(Received via mailing list)
On Wed, Nov 19, 2008 at 12:35 PM, Demetirck Demetrickn
<demetrickn@hotmail.com> wrote:
> loop.
> Is there anyway I can  static cast or do a type conversion in ruby ?
> --
> Posted via http://www.ruby-forum.com/.
>
>

It doesn't sound like your error is necessarily what you think it is.
That
error happens when you do something like:
  a = [1, 2, 3, 4, 5]
  i = nil
  a[i]

You can convert most objects (including nil) to an integer with the to_i
method, but that probably isn't going to fix anything.  nil.to_i is
always 0.

Post some code and someone here will likely be able to spot your error.
96f67d16abbcfed1c9f54b5d6fa87619?d=identicon&s=25 Teja Venkat (venkatateja)
on 2014-03-26 05:54
rand_id = rand(0..@abc.hits.size-1) @abc =
@abc.hits[rand_id].primary_key.to_i

i am getting an no implicit conversion from nil to integer .please
suggest any solution

error is coming from the C code inside the Ruby interpreter. A core
class, implemented in C, is being handed a nil when it expects an
Integer. It may have a #to_i but it doesn't have a #to_int and so the
result is the TypeError.

but how can i change there please suggest solution..
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.