小编Jar*_*eck的帖子

强制布尔值

给定一个表达式可能返回真值或零,

truthy_or_nil = [true, 'truthy', nil].sample
Run Code Online (Sandbox Code Playgroud)

如果没有我的同事或者玩家抱怨,我如何将结果强制转换为布尔值?

!!truthy_or_nil # Hard to see the !! on a long line, unclear
truthy_or_nil || false # Linter complains "you can simplify this"
!truthy_or_nil.nil? # Unclear on a long line
truthy_or_nil ? true : false # Hard to see on long line, too much typing
Run Code Online (Sandbox Code Playgroud)

我查看了以下问题,发现它们不相关:

如果这个问题被确定为过于宽泛,我会理解.如果是这样,有没有更好的地方问它?

ruby

2
推荐指数
1
解决办法
2851
查看次数

为什么 rubocop 推荐 require: false in Gemfile?

rubocop自述说:

如果您更愿意使用 bundler 安装 RuboCop,请不要在您的 Gemfile 中要求它:

gem 'rubocop', require: false

为什么不?

在一些项目中,我让 bundler 需要 rubocop,并且没有遇到任何问题。我还将 rubocop 放在我的group :development, :test块中,因为我在生产中不需要它。

ruby rubocop

2
推荐指数
1
解决办法
1242
查看次数

测试排队的电子邮件数量?

我们可以检查enqueued_jobs.length,前提是电子邮件是唯一可能的后台作业类型。

it 'sends exactly one, particular email' do
  expect { post :create }.to(
    # First, we can check about the particular email we care about.
    have_enqueued_mail(MyMailer, :my_particular_email)
  )

  # But we also have to check that no other email was sent.
  expect(ActiveJob::Base.queue_adapter.enqueued_jobs.length).to eq(1)
end
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法来断言:

  1. MyMailer.my_particular_email已排队,
  2. 没有其他电子邮件排队,
  3. 我们不关心其他非电子邮件后台作业是否已排队

ruby rspec ruby-on-rails rspec-rails rails-activejob

1
推荐指数
1
解决办法
1596
查看次数

如何对整数字符串数组求和?

问题:将数组字符串元素转换为整数求和。我的代码:

ch = ["+7", "-3", "+10", "0"]

ch.to_i
soma = 0
string.each do |ch| 
    if ch.isdigit() 
        soma += ch.to_i
    end
end
p(soma)
Run Code Online (Sandbox Code Playgroud)

错误:

Traceback (most recent call last):
main.rb:2:in `<main>': undefined method `to_i' for ["+7", "-3", "+10", "0"]:Array (NoMethodError)
Did you mean?  to_s
               to_a
               to_h
Run Code Online (Sandbox Code Playgroud)

ruby arrays string integer

-1
推荐指数
1
解决办法
516
查看次数