Apple - Create an APFS RAM disk
It works if you create a JHFS+ volume first and convert it to APFS in a second step:
DISK_ID=$(hdiutil attach -nomount ram://$((<number_of_blocks>)))
diskutil eraseDisk JHFS+ "RAM Disk" $DISK_ID
diskutil apfs convert $(tr -d ' '<<<${DISK_ID}s2)
If the RAM disk has a size of 2 GiB (4 * 1024 * 1024)(block_size) or smaller no EFI partition is created and the 3rd command is: diskutil apfs convert $(tr -d ' '<<<${DISK_ID}s1)
or more generally:
DISK_ID=$(hdiutil attach -nomount ram://$((<number_of_blocks>)))
SIZE=$(diskutil info $DISK_ID | awk -F'[^0-9]*' '/Disk Size/ {print$4}')
diskutil eraseDisk JHFS+ "RAM Disk" $DISK_ID
if [ $SIZE -le 2147483648 ]; then diskutil apfs convert $(tr -d ' '<<<${DISK_ID}s1); else diskutil apfs convert $(tr -d ' '<<<${DISK_ID}s2); fi
Result:
...
/dev/disk2 (disk image):
#: TYPE NAME SIZE IDENTIFIER
0: GUID_partition_scheme +4.3 GB disk2
1: EFI EFI 209.7 MB disk2s1
2: Apple_APFS Container disk3 4.0 GB disk2s2
/dev/disk3 (synthesized):
#: TYPE NAME SIZE IDENTIFIER
0: APFS Container Scheme - +4.0 GB disk3
Physical Store disk2s2
1: APFS Volume RAM Disk 32.8 KB disk3s1