开发者

Ruby hash value converts to string, don't know why

I have a 'strange' problem, the following code converts the location lat value into a string (With a + sign for each iteration) leading to an eventual exception when comparing values. I've tried the code with values for another location and it works fine. The only difference is that the other numbers were negatives.

location= {:lng => 2.0781,:lat => 41.2899}
while location[:lat] < top
      sleep(1)
      checkTweets(location)
      bottom+=0.075
      location[:lat] = bottom
end

The issue occurs before entering the check tweets location. The values for the hash are as follows

To to conclude, my question is can anyone explain to me why location[:lat] ends up being a string in this circumstance?

Bottom is initialized as 30.0400 which is assigned to the :lat value. The checkTweets method simply writes a file based on a mongodb query.

Right I found the solution to this. It was the twitter library which was turning the Hash float values into strings.

Am I wrong in assuming that the scope of the variable in the checkTweets meth开发者_StackOverflowod should not impact the location variable here, they are both declared in seperate methods, they are not class level.


I wrong in assuming that the scope of the variable in the checkTweets method should not impact the location variable here, they are both declared in seperate methods, they are not class level.

No, but variable scope is not the issue here. The location variable is local to your method and as such cannot be changed by the checkTweets method. That is correct.

However the object that is referenced by the location variable can be changed from the checkTweets method and that is exactly what happens (though I have to say that mutating arguments is very bad style).

A little example to illustrate reference semantics and mutation in ruby:

def f1(arr)
  arr = [1,2,3] # Changes the variable arr, which is local to f1
                # This change is not visible on the outside
end

def f2(arr)
  arr.concat [1,2,3] # Changes the object that arr refers to
                     # This change will be visible any place where the same
                     # array is referenced
end

foo = [42,23]
f1(foo)
# foo is still [42, 23]
f2(foo)
# foo is now [42, 23, 1, 2, 3]

Here the variable foo hasn't been changed to refer to another object (that would not be possible from inside a method), but the object that foo refers to has been changed. The same happens in your checkTweets method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜