以下两个代码段之间有什么区别?

时间:2019-06-14 20:34:35

标签: ruby

以下两个代码段应该相同,但是它们返回不同的输出

movies = {
  StarWars: 4.8, 
  Divergent: 4.7
  }

puts "What would you like to do? "

choice = gets.chomp

case choice
when "add"
  puts "What movie would you like to add? "
  title = gets.chomp
  if movies[title.to_sym] = nil
    puts "What rating does the movie have? "
    rating = gets.chomp
    movies[title.to_sym] = rating.to_i
    puts "#{title} has been added"
  else
    puts "That movie already exists! Its rating is #{movies[title.to_sym]}."
  end
movies = {
  StarWars: 4.8, 
  Divergent: 4.7
  }

puts "What would you like to do? "

choice = gets.chomp

case choice
when "add"
  puts "What movie would you like to add? "
  title = gets.chomp
  if movies[title.to_sym].nil?
    puts "What rating does the movie have? "
    rating = gets.chomp
    movies[title.to_sym] = rating.to_i
    puts "#{title} has been added"
  else
    puts "That movie already exists! Its rating is #{movies[title.to_sym]}."
  end

输出1: 你想干什么? 加 您要添加什么电影? 星球大战 那部电影已经存在!评分是。

输出2: 你想干什么? 加 您要添加什么电影? 星球大战 那部电影已经存在!评分是4.8。

PS:我没有粘贴其余的代码,因为这是不相关的

1 个答案:

答案 0 :(得分:1)

文件之间的差异归结为这两行:

if movies[title.to_sym] = nil

if movies[title.to_sym].nil?

第一个是赋值语句,第二个是测试从movies哈希中获取的值是否为nil

问题在于赋值语句的结果被有条件地评估为错误布尔值:moves[title.to_sym]的值设置为nil,然后条件量为if nil

流行测验。以下程序的输出是什么?为什么?

h = {a: 42}

p "one" if h[:a] == 42
p "two" if h[:a] == nil
p "three" if h[:a] = 42
p "four" if h[:a] = nil

答案:

  

“一个”“三个”(第一个条件是成功的典型比较;第二个是失败的典型比较;第三个是返回真实值42的赋值;第四个是返回a的真实值)假值,无)


尽管存在争议,但Yoda conditions解决了这个偶然的分配错误:

p "yoda assignment" if nil = 42

输出:

(repl):1: Can't assign to nil
p "yoda assignment" if nil = 42