简体   繁体   中英

Ruby, how can i compare a string with a specific element of array?

I create an array from a text file which contains the english irregular verbs. I want the code to ask me the verbs in random order letting me proceed only if I respond correctly. I need to compare a string with an element of array. I wrote this:

a = []
File.open('documents/programmi_test/verbi.txt') do |f|
  f.lines.each do |line|
    a <<line.split.map(&:to_s)
  end
end
puts ''
b = rand(3)
puts a[b][0]
puts 'infinitive'
infinitive = gets.chomp
  if infinitive = a[b][1]    #--> write like this, I receive alway "true"
    puts 'simple past'
  else
    puts 'retry'
  end
pastsimple = gets.chomp
  if pastsimple == a[b][2]    #--> write like this, I receive alway "false"
    puts 'past participle'
  else
    puts 'retry'
  end
pastpart = gets.chomp
  if pastpart == a[b][3]
    puts 'compliments'
  else
    puts 'oh, no'
  end

can somebody help me?

if infinitive = a[b][1] is assigning to inifinitive the value of a[b][1] , unlike pastsimple == a[b][2] that's a comparation between both values.

You could try replacing the = for == .

a = []

File.open('documents/programmi_test/verbi.txt') do |file|
  file.lines.each do |line|
    a << line.split.map(&:to_s)
  end
end

puts ''
b = rand(3)
puts a[b][0]
puts 'infinitive'

infinitive = gets.chomp
puts infinitive == a[b][1] ? 'simple past' : 'retry'
pastsimple = gets.chomp
puts pastsimple == a[b][2] ? 'past participle' : 'retry'
pastpart = gets.chomp
puts pastpart == a[b][3] ? 'compliments' : 'oh, no'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM