How do I output the last matrix block?
Twig comes with a last filter which you should be able to use, so with your entry.gallery  you can do:

{% set lastBlock = entry.gallery|last %}


Which will return the last element in the sequence, there's more info in the twig docs:


  The last filter returns the last "element" of a sequence, a mapping, or a string:


Twig last filter