How do I differentiate between "pear - 梨 (lí)" and “to leave - 离 (lí)”? They both sound exactly the same, so do I just follow the sentence to see which it is? Or is there another way to dissolve this ambiguity? I have searched online for this, but did not manage to find anything.
The general case is discussed here: How to distinguish two words the same pronunciation but different meaning (gāo jià)
For 梨 (lí) and 离 (lí) in particular, they're readily differentiated by their parts of speech. They're unlikely to be confusable in spoken Chinese: outside of contrived examples, you can't take one and swap it for the other and get a grammatical sentence.
梨 = "pear" is strictly a noun, so we can say 我买了几个梨 = "I bought a few pears", 我喜欢吃梨 = "I like to eat pears". Also it's almost only ever going to arise when we're talking about food (perhaps there are exceptions for proper nouns).
离 by itself is usually used as a preposition, such as in 图书馆离地铁站很近 = "the library is close to the subway station". When used as a verb, it's almost always used as part of a larger word, like 我离不开他 = "I can't leave him" or 我远离家乡 = "I'm a long way from home", or even in chengyu like 不离不弃 or 形影不离.
And we can also simply use 梨子 instead of 梨.