0

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

6
  • 1
    Don't do that. Your code is vulnerable. Commented Apr 25, 2017 at 4:04
  • What can i do to improve it Commented Apr 25, 2017 at 4:06
  • I need pass variables Commented Apr 25, 2017 at 4:07
  • Don't use eval() Commented Apr 25, 2017 at 4:09
  • I agree, I'll look for an alternative thanks Commented Apr 25, 2017 at 4:10

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

2 Comments

I believe it’s vice versa: params[:salutation] is a string instance passed to an array expecting an integer index.
@mudasobwa Now that I read this code I realize it's a classic case of trying to concatenate string + integer + string which always generates an error. The hash is a red-herring. The strange eval layer adds a lot of confusion. Thanks for pointing out that I didn't have it pinned down right though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.