tags:

views:

75

answers:

4
k=[]

path="E:/expr/amit.txt"
name="amit"

File.open("amit.txt").each do |l| 
  k<< l
end

puts k[0]
puts name.eql?("k[0]")

O/p amit

false

why o/p containing false??it should give true

+3  A: 

The value of name is "amit". You're checking whether the string "amit" is equal to the string "k[0]". It's not, so you get false.

What you probably meant to do was name.eql?(k[0]), which would check whether the value k[0] is "amit". However this would still return false, because k[0] is "amit\n", not "amit".

To fix this, you should do k << l.chomp instead of k << l to remove the trailing \n.

sepp2k
but i also given puts k[0] and that giving amit my file content are
AMIT
AMIT: You can't see the `\n` with puts. You should use `p` instead.
sepp2k
sepp2k i tried with k << l.chomp but its giving me false
AMIT
A: 

You're testing the string "amit" against the string "k[0]". I think you probably want puts name.eql?(k[0])

Chris
puts name.eql?(k[0]) also am getting false..
AMIT
+1  A: 

Try doing a chomp before you save the k

k=[]
name="amit"
File.foreach("file") do  |line|
  k<<line.chomp
end
p k.grep(name)
puts name.eql?(k[0])

output

$ cat file
amit
submit

$ ruby test.rb
["amit"]
true
ghostdog74
all in vain i tried with k << l.chomp but still getting false
AMIT
why don't you show the contents of your amit.txt file in your question!!?
ghostdog74
yaa sure content of my amit.txt is
AMIT
amit sumit this is content of file amit.txt
AMIT
means amit and sumit are in two differnt line like amit sumit
AMIT
sorry am not able to put amit and sumit in two line
AMIT
edit your question and put your file content in. That way, others can see it more clearly. And, btw, I don't have any problem with your code. See edit.
ghostdog74
whats happening this is my o/p []false
AMIT
running ruby 1.8.6 (2007-03-13 patchlevel 0) [i386-mswin32]
AMIT
puts k.grep(name) is printing nothing
AMIT
thanks ghost i run this code to some other machine is working there i don't why whenever am running it scite am getting problem any way thanks for your help
AMIT
+1  A: 

If you're not sure why your program isn't working, .inspect is your friend.

k=[]

path="E:/expr/amit.txt"
name="amit"

File.open("amit.txt").each do |l|
  puts "Debugging: l is #{l.inspect}"
  k<< l
end

puts k[0]
puts name.eql?("k[0]")
puts "Debugging: name is #{name.inspect}, while k[0] is #{k[0].inspect}"
Andrew Grimm