The subnet mask is used to "group together" network interfaces [more or less = computers ] which can speak directly to each other.
A gateway CAN NOT be the same as a subnet, but a gateway (with a few technical exceptions) needs to be in the same subnet as the machines connected to it.
A subnet mask represents a number of bits, which make up a range. Using some (for a computer at least) simple binary maths, it can easily work out if another address is in the same subnet/physical network. Subnets are (generally) a group of numbers which are a power of 2.
By way of example - Take the common subnet 255.255.255.0. Each "." represents a part of the IP addreess. So if a computer has an IP address of 192.168.1.2, and a netmask of 255.255.255.0, it means that any machine which has an IP address of 192.168.1.X is locally attached and does not need to go through a router.
It is possible, and indeed on non-home connections very common to have different subnets, for example, many point-to-point connections will have a subnet of 255.255.255.252, which provides 4 IP addresses, of which only 2 are actually usable for machines - 1 for each end of the link. Similarly, because IP space is at a premium, a block of 256 IP's [called a class C] can be divided up on subnet boundaries, for example into 16 sets of 16 IP's, with a netmask of 255.255.255.240, and then given to different networks.
It is not quite correct to say that all IP addresses not in a subnet will be routed out the [default] gateway - in fact, a network does not even need to have a default gateway, and will still work with limited functionality.
There are 2 parts to understanding this -
If an address is not in the same subnet as the originating PC (as defined by the
netmask), a "next hop" can be specified. Thus if I want to see different parts of
a network/the internet through different computers I can specify different "next hops"
for various IP addresses. In addition, instead of specifying IP addresses, I can
specify ranges of IP addresses using netmasks.
A default route is nothing more then a slightly special case of a network with
a "next hop" of the router - the special case being the netmask 0.0.0.0, which means
all addresses. (Where an IP address is matched by multiple routes, the one with
the smallest netmask (ie largest number for the netmask) that matches
the route is used.