# From a file to an array of words

**URL:** <https://www.ruby-forum.com/t/from-a-file-to-an-array-of-words/48994>\
**Category:** Ruby\
**Created:** [November 28, 2005, 1:23pm UTC](https://www.ruby-forum.com/t/from-a-file-to-an-array-of-words/48994 "2005-11-28T13:23:38Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![ngoc](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/e495f1/32.png) [@ngoc](https://www.ruby-forum.com/u/ngoc)\
**Post date:** [November 28, 2005, 1:23pm UTC](https://www.ruby-forum.com/t/from-a-file-to-an-array-of-words/48994/1 "2005-11-28T13:23:38Z")

</div>

I want to compare two text(html) files. “diff” command in Linux compares  
only by line.  
In Ruby, I can use “File.readlines” and “split” later. Is there a single  
function(method) to go from a file to an array of words.  
Thanks

---

<div class="post-metadata">

**Author:** ![ngoc](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/e495f1/32.png) [@ngoc](https://www.ruby-forum.com/u/ngoc)\
**Post date:** [November 28, 2005, 1:47pm UTC](https://www.ruby-forum.com/t/from-a-file-to-an-array-of-words/48994/2 "2005-11-28T13:47:53Z")

</div>

ngoc wrote:

> I want to compare two text(html) files. “diff” command in Linux  
> compares only by line.  
> In Ruby, I can use “File.readlines” and “split” later. Is there a  
> single function(method) to go from a file to an array of words.

What is a word in your context? If you want an array of tokens  
consisting  
only of word characters you can do

words = File.read(file\_name).scan(/\w+/)

Note though that this is memory intensive for large files. This is a  
bit  
more efficient:

words = File.open(file\_name) do |io|  
io.inject([]) {|w, line| w.concat( line.scan( /\w+/ ) )}  
end

Kind regards

```
robert
```

---

<div class="post-metadata">

**Author:** ![ngoc](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/e495f1/32.png) [@ngoc](https://www.ruby-forum.com/u/ngoc)\
**Post date:** [November 28, 2005, 1:51pm UTC](https://www.ruby-forum.com/t/from-a-file-to-an-array-of-words/48994/3 "2005-11-28T13:51:56Z")

</div>

Not a single but basically,

File.read( fname ).split(/\s+/)
