This is a test version of Biostars. For the public version, visit https://www.biostars.org.
How To Read Bam File Line By Line Using Ruby

Dear all,

I am trying to read bam file line by line by using ruby scripts. Although there is ruby gem bio-samtools(http://rubygems.org/gems/bio-samtools), I don't find a way to read the whole bam file line by line(can get the alignments for given genomic regions). Any suggestion will be appreciated.

BTW, I have used IO.open("samtools view sample1.bam").each do {|x| ...}, however it will put the whole bam file into the memory first.

bam ruby

Really? At least in C, the whole idea of popen() is NOT to read the whole file into memory.

1 answer

I know it's a 9 year old question, but I think you could make Ruby bindings for htslib or noodles. No one would do such a thing? I'm trying to make ruby-htslib. It's still buggy, though.

require 'htslib'

bam = HTS::Bam.open("foo.bam")

bam.each do |r|
  pp name: r.qname,
     flag: r.flag,
     chrm: r.chrom,
     strt: r.pos + 1,
     mapq: r.mapq,
     cigr: r.cigar.to_s,
     mchr: r.mate_chrom,
     mpos: r.mpos + 1,
     isiz: r.isize,
     seqs: r.seq,
     qual: r.qual.map { |i| (i + 33).chr }.join,
     MC:   r.aux("MC")
end

bam.close

Log in to answer this question.