I'm making a wiki in Sinatra and I have the following code, which works, it just strikes me as a little bit clunky. I'm trying to get all the wiki entries saved in "pages" and display them on the homepage as links.
get "/" do
@entries = Dir["pages/*.txt"]
@entries.map! { |f| f.split '/' }
@entries.flatten!
@entries.delete_if { |p| p == "pages" }
@entries = @entries.sample(5)
erb :welcome, layout: :page
end
If any ruby genius would like to demonstrate eloquent ruby I would be very grateful!
The most obvious thing is to chain method calls. Doing this also leads to a more "functional programming" style. Note how I replaced
delete_if
(which mutates the array) withreject
(which doesn't). I also removed the "bang" methods because using mutating methods is unnecessary here. These shouldn't be the first thing you reach for, because they can sometimes have unintended effects.For example I recently found a co-worker had written
return string.gsub!(" ", "")
or something like that. The problem isgsub!
returns nil. Usinggsub
instead worked.