sawa sawa - 4 months ago 7
Ruby Question

Using `Array#[]` versus `find("...:nth-child(n)")`

When I want to pick up a certain node out of multiple nodes of the same type by its index, there are the following ways to do so:

some_table_node.find("tr:nth-child(3)").find("td:nth-child(5)")

some_table_node.all("tr")[2].all("td")[4]


Which way is better? Can you provide arguments with your preference?

Answer

find waits, all does not. Generally this means that find is less brittle (and superior). You should also be able to simplify the former to:

some_table_node.find("tr:nth-child(3) td:nth-child(5)")