gpt4 book ai didi

ruby-on-rails - 定义变量时简化 Ruby 控制流

转载 作者:数据小太阳 更新时间:2023-10-29 08:04:59 27 4
gpt4 key购买 nike

我在 Rails 应用的页面上定义了三个变量:

  if current_user
if Vote.where(:user_id => current_user.id, :post_id => post.id, :direction => 0).count > 0
active = ' upactive'
elsif Vote.where(:user_id => current_user.id, :post_id => post.id, :direction => 1).count > 0
active = ' downactive'
end
end

unless Vote.group(:post_id).where(:post_id => @posts.map(&:id), :direction => 0).count[post.id] == nil
upvotes = Vote.group(:post_id).where(:post_id => @posts.map(&:id), :direction => 0).count[post.id]
else
upvotes = 0
end

unless Vote.group(:post_id).where(:post_id => @posts.map(&:id), :direction => 1).count[post.id] == nil
downvotes = Vote.group(:post_id).where(:post_id => @posts.map(&:id), :direction => 1).count[post.id]
else
downvotes = 0
end

我注意到 if 和 unless 语句中有相当多的重复代码。我怎样才能写出三个等于上面的变量声明,确保变量总是 0 而不是 nil

最佳答案

您可以在此处使用条件赋值运算符来帮助减少代码。例如:

if current_user
if Vote.where(:user_id => current_user.id, :post_id => post.id, :direction => 0).count > 0
active = ' upactive'
elsif Vote.where(:user_id => current_user.id, :post_id => post.id, :direction => 1).count > 0
active = ' downactive'
end
end

upvotes = Vote.group(:post_id).where(:post_id => @posts.map(&:id), :direction => 0).count[post.id] || 0
downvotes = Vote.group(:post_id).where(:post_id => @posts.map(&:id), :direction => 1).count[post.id] || 0

条件赋值运算符本质上是说如果第一部分的计算结果为 nil,则使用右侧作为默认值。

关于ruby-on-rails - 定义变量时简化 Ruby 控制流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14271186/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com