zzero
zzero

Reputation: 154

ruby TypeError - no implicit conversion of Fixnum into String?

Im trying to eval this function and appears

this error

TypeError - no implicit conversion of Fixnum into String

eval("File.open('nagai.txt', 'a+') do |f| \n   f. puts parts["  +    params[:salutation].to_i + "] \n end")

how I could solve

Upvotes: 0

Views: 778

Answers (1)

tadman
tadman

Reputation: 211590

This code is extremely risky and I can't see a reason for doing this in the first place. Remove the eval and you get this very ordinary code:

File.open('nagai.txt', 'a+') do |f|
  f.puts parts[params[:salutation]]
end

The error comes from trying to concatenate a Fixnum/Integer to a String in the process of constructing the code you then eval. This code is invalid and yields the same error:

"1" + 1

Ruby isn't like other languages such as JavaScript, PHP or Perl which arbitrarily convert integers to strings and vice-versa. There's a hard separation between the two and any conversion must be specified with things like .to_s or .to_i.

That fixed version should be equivalent. If you need to defer this to some later point in time, you can write a method:

def write_nagai(params)
  File.open('nagai.txt', 'a+') do |f|
    f.puts parts[params[:salutation]]
  end
end

Upvotes: 3

Related Questions