with puts command below output contents of variable new_array
, contents @ index 0, have stored in variable called first element
. output class of first_element
, nil
class returned. can explain why is? also, there better way this?
thanks!
new_array = [] first_element = new_array[0] array = ["1", "2"] array.each |x| new_array << x.to_i end puts new_array[0] puts first_element.class
output
$ruby testing_2.rb 1 nilclass
when new_array
initialized, it's initialized empty array. means has 0 elements. if try access index, you're trying access index doesn't exist. in ruby, referred nil.
Comments
Post a Comment