-2

我正在尝试使用 for 循环和 if 条件来使用File.openputs函数创建文件。我的代码是

I want to write these entries only if it is not null. How to do it?

Edit: Full code is

需要'fileutils'需要'json'需要'open-uri'需要'pp'

数据 = JSON.parse('数据')

数组 = 数据如果数组 &.any?

Drafts_dir = File.expand_path('../drats', dir ) FileUtils.mkdir_p(drafts_dir)

array.each 做 |entry|

File.open(File.join(drafts_dir, "#{entry['twitter']}.md"), 'wb') do |draft|
keys = 1.upto(6).map { |i| "key_#{i}" }

values = keys.map { |k| "<img src='#{entry['image']} alt='image'>" if entry['image']}
# you can also do values = entry.values_at(*keys)

str = values.reject do |val|
  val.nil? || val.length == 0 
end.join("\n")

draft.puts str  
end

结束结束

I need the the file `mark.md` as

https://somesite.com/image.png' alt='image'>
https://twitter.com/mark'>mark


and `kevin.md` likewise.
4

2 回答 2

2

您可以从数组构建字符串,拒绝空值:

keys = 1.upto(6).map { |i| "key_#{i}" }

values = keys.map { |k| entry[k] }
# you can also do values = entry.values_at(*keys)

str = values.reject do |val|
  val.nil? || val.length == 0 
end.join("\n")

draft.puts str

更新以响应您更改的问题。做这个:

array.each do |entry|
  File.open(File.join(drafts_dir, "#{entry['twitter']}.md"), 'wb') do |draft| 
    next unless ['image', 'twitter'].all? { |k| entry[k]&.length > 1 }
    str = [
      "<img src='#{entry['image']} alt='image'>",
      "<a href='https://twitter.com/#{entry['twitter']}'>#{entry['twitter']}</a>"
    ].join("\n")
    draft.puts str  
  end
end
于 2019-09-13T18:31:26.387 回答
2

假设,你entry是哈希。

final_string = ''
entry.each_value { |value| final_string << "#{value}\n" }
puts final_string
于 2019-09-13T18:32:30.093 回答