我有一个矢量矢量,我想将它们分成单独的矢量。
<div>
<% @hosts.each do |host| %>
<div class="row">
<% if host.rooms.any? { |room| room.bookings.empty? } %>
<!-- if a host has rooms without bookings then they are definitely going to have free rooms -->
<div class="small-3 medium-4 large-4 columns">
<%= image_tag host.picture_url %>
</div>
<div class="small-9 medium-8 large-8 columns">
<p>Host #<%= host.id %>: <%= host.name %></p>
<p><%= host.address %></p>
<% host.rooms.each do |room| %>
<!-- display information on free rooms -->
<% if room.bookings.empty? %>
<p>room #<%= room.id %> is available (0 booked, <%= room.capacity %> free out of <%= room.capacity %>)</p>
<% else %>
<!-- for the rooms with bookings - check if rooms are fully booked first -->
<% unless ((room.capacity - room.bookings.first.number_of_guests) == 0) %>
<% total_booked = room.bookings.first.number_of_guests %>
<% space = room.capacity - total_booked %>
<p>room #<%= room.id %> is available (<%= total_booked %> booked, <%= space %> free out of <%= room.capacity %>)</p>
<% end %>
<% end %>
<% end %>
</div>
<% else %>
<!-- if all the rooms belonging to a host are booked - check if all the rooms are fully booked -->
<% if !(host.rooms.all? { |room| (room.capacity - room.bookings.first.number_of_guests) == 0 }) %>
<!-- If all the rooms are fully booked there is nothing to display so there is no else block. Check the rooms individually for availability -->
<div class="small-3 medium-4 large-4 columns">
<%= image_tag host.picture_url %>
</div>
<div class="small-9 medium-8 large-4 columns">
<p>Host #<%= host.id %>: <%= host.name %></p>
<p><%= host.address %></p>
<% host.rooms.each do |room| %>
<% unless ((room.capacity - room.bookings.first.number_of_guests) == 0) %>
<% total_booked = room.bookings.first.number_of_guests %>
<% space = room.capacity - total_booked %>
<p>room #<%= room.id %> is available (<%= total_booked %> booked, <%= space %> free out of <%= room.capacity %>)</p>
<% end %>
<% end %>
</div>
<% end %>
<% end %>
</div>
<% end %>
</div>
答案 0 :(得分:2)
你的向量中已经有了单独的向量。存在多种访问方式,尤其是nth
。
分离可以在很多方面发生。以下是您可以在REPL中尝试的一些示例。
一种常见的模式是使用let with在本地上下文中单独绑定它们:
(let [first-elem (nth my-vec 0)
third-elem (nth my-vec 2)]
(str "First: " first-elem "\Third: " third-elem))
这通常也是通过析构函数完成的:
(let [[first-elem _ third-elem] my-vec] ;; _ is idiomatic for ignored binding
(str "First: " first-elem "\Third: " third-elem))
另一种常见情况是从各个元素构建一个惰性序列,例如:
(map-indexed (fn [i v] (str "Elem " i ": " v)) my-vec)
或只是迭代副作用
(doseq [v my-vec]
(println v))
;; in Clojure 1.7 prefer
(run! println my-vec)
或将一个存储为可变状态
(def current-choice (atom nil))
(swap! current-choice (nth my-vec 2))
@current-choice
当您了解Clojure系列时,您会发现更多。随意继续实验。