How to convert a hash into a string in ruby - ruby

I'm trying to do an wolfram api using Ruby. I found that you can create a hash from text you put to find an answer on wolfram page. I managed to do something like this in my controller:
class CountController < ApplicationController
def index
#result = Wolfram.fetch('6*7')
#hash = Wolfram::HashPresenter.new(#result).to_hash
#pods = #hash[:pods]
end
end
When I want to show this on my site I do something like this in my view:
<p>
<b>Result:</b>
<%= #result %>
<br>
<b>Hash:</b>
<%= #hash %>
<br>
<b>Hash.pods</b>
<%= #pods["Input"]%>
<br>
</p>
And I have something like this on my page:
Result: #<Wolfram::Result:0x00000004758b78>
Hash: {:pods=>{"Input"=>["6×7"], "Result"=>["42"], "Number name"=>["forty-two"], "Number line"=>[""], "Illustration"=>["6 | \n | 7"]}, :assumptions=>{}}
Hash.pods ["6×7"]
I'd like to have just 6x7 instead of ["6x7"]. Is there a solution to change this hash into a string?

The reason why it is being displayed like [6x7] is that your hash stores it within an array. Displaying it any other way will be misleading. However you can do it with:
Hash[#hash.map {|key, value| [key, (value.kind_of?(Array) && value.size == 1) ? value.first : value }]

Related

ruby middleman hash traversal

New to hashes. I've got a hash from middleman data file which is automatically generated by contentful_middleman. Basically
data.space.homepage = {
"PCWLCTeTCKsaoGGSQOc6i"=>{
"id"=>"PCWLCTeTCKsaoGGSQOc6i",
"pageTitle"=>"Page Title",
"pageContent"=>"page content",
}
}
Because PCWLCTeTCKsaoGGSQOc6i is automatically generated I have to be able to reference it without using this key.
I don't know why exactly but the underscore here gets me where I need to be:
<% data.space.homepage.each do |_, item| %>
<h1 class="tag"><%= item.pageTitle %></h1>
<% end %>
I'd like to be able to access pageTitle and pageContent without looping over the data but I can't figure out if that's possible without explicitly using the key PCWLCTeTCKsaoGGSQOc6i
If homepage is a hash with a single pair of key/value, you can use :
title, content = data.space.homepage.values.first.values_at('pageTitle', 'pageContent')
title #=> "Page Title"
content #=> "page content"
The id is :
homepage.keys.first #=> "PCWLCTeTCKsaoGGSQOc6i"

Ruby - trying to make hashtags within string into links

I am trying to make the hashtags within a string into links.
e.g. I'd like a string that's currently: "I'm a string which contains a #hashtag" to transform into: "I'm a string which contains #hashtag"
The code that I have at the moment is as follows:
<% #messages.each do |message| %>
<% string = message.content %>
<% hashtaglinks = string.scan(/#(\d*)/).flatten %>
<% hashtaglinks.each do |tag| %>
<li><%= string = string.gsub(/##{tag}\b/, link_to("google", "##{tag}") %><li>
<% end %>
<% end %>
I've been trying (in vain) for several hours to get this to work, reading through many similar stackoverflow threads- but frustration has got the better of me, and as a beginner rubyist, I'd be really appreciate it if someone could please help me out!
The code in my 'server.rb' is as follows:
get '/' do
#messages = Message.all
erb :index
end
post '/messages' do
content = params["content"]
hashtags = params["content"].scan(/#\w+/).flatten.map{|hashtag|
Hashtag.first_or_create(:text => hashtag)}
Message.create(:content => content, :hashtags => hashtags)
redirect to('/')
end
get '/hashtags/:text' do
hashtag = Hashtag.first(:text => params[:text])
#messages = hashtag ? hashtag.messages : []
erb :index
end
helpers do
def link_to(url,text=url,opts={})
attributes = ""
opts.each { |key,value| attributes << key.to_s << "=\"" << value << "\" "}
"<a href=\"#{url}\" #{attributes}>#{text}</a>"
end
end
Here is the code to get you started. This should replace (in-place) the hashtags in the string with the links:
<% string.gsub!(/#\w+/) do |tag| %>
<% link_to("##{tag}", url_you_want_to_replace_hashtag_with) %>
<% end %>
You may need to use html_safe on the string to display it afterwards.
The regex doesn't account for more complex cases, like what do you do in case of ##tag0 or #tag1#tag2. Should tag0 and tag2 be considered hashtags? Also, you may want to change \w to something like [a-zA-Z0-9] if you want to limit the tags to alphanumerics and digits only.

accessing mongodb document field names and its values through iteration

Let's say I have a mongodb document in the products collection:
{
"_id" : ObjectId("51b1eac0311b6dd93a000001"),
"name" : "Apple",
"price" : "34.45"
}
products_controller.rb for def show part:
def show
#product = Product.find(params[:id])
end
I imagine the code would seem like below in the show.html.erb:
<% #product.each do |f|%>
<p>f.label</p> # this is only an image code
<p>f.value</p> # this is only an image code
<% end %>
How the code at the lines 2 and 3 on Rails 3 should look like in a generic way so it would show like? :
name: Apple
price: 34.45
Number of fields can be 20, so I don't want to write the same code for 20 fields.
I'm using Rails 3 with Mongoid. I think it's not a mongodb-specific question.
Try this:
foreach (var item in YourcollectionName)
{
var name = item.name;
var price = item.price;
}
Mongoid models have an attributes method that returns a hash of the attributes. If you iterate over that hash you'll be yielded the name and value of each entry.
For example
<% #product.attributes.each do |name, value| %>
<p>
<%= name%> : <%= value %>
</p>
<% end %>
You'd need some more sophisticated formatting code for pretty output for all the kinds of values you might get (dates, arrays, hashes etc.)

Convert string to variable name in ruby

I have variables
<% mon_has_two_sets_of_working_hours = 0 %>
<% tue_has_two_sets_of_working_hours = 0 %>
<% wed_has_two_sets_of_working_hours = 0 %>
I want to change the values of these variables dynamically.
<% days_array = ['mon', 'tue', 'wed'] %>
<% days_array.each do |day| %>
<% if condition? %>
# here i want to set %>
<% "#{day}__has_two_sets_of_working_hours" = 1 %>
end
end
The value is not getting assigned. Is there any way to assign value to variable dynamically?
I don't think there is a way to do this. There is with instance or class variables, but with local variables there is very rarely a good need.
In your case you really should have the data in a hash. Also, logic like this really does not belong in erb. You want something like:
working_hour_sets = %w[mon tue wed thu fri sat sun].inject({}) do |hash, day|
hash[day]=0;
hash
end
# puts working_hour_sets #=> {"wed"=>0, "sun"=>0, "thu"=>0, "mon"=>0, "tue"=>0, "sat"=>0, "fri"=>0}
working_hour_sets.each do |day, value|
working_hour_sets[day] = 1 if condition?
end
Now, I know this question is a bit old, but there is an easier way to do this and is using the standard Ruby send method. This is actually one of the methods that make Ruby so agile in the metaprogramming world.
This is actually a config setting I use in a Rails app:
# In a YAML
twitter:
consumer_key: 'CONSUMER-KEY'
consumer_secret: 'CONSUMER-SECRET'
oauth_token: 'OAUTH-KEY'
oauth_token_secret: 'OAUTH-SECRET'
...
# And in your file.rb
config = YAML.load_file(Rails.root.join("config", "social_keys.yml"))[Rails.env]['twitter']
Twitter.configure do |twitter|
config.each_key do |k|
twitter.send("#{k}=", config[k])
end
end
It's DRY and very easy to understand. :)
Yet another answer to this old question.
In my scenario, I wanted to count how many times a day showed up in an array of days (day_array). I didn't need to know if a day didn't show up in day_array, so I didn't initialize the days_count hash as gunn did in his answer.
Here's how I did it:
def count_days(day_array)
days_count = {}
day_array.each do |day|
days_count[day].nil? ? days_count[day] = 1 : days_count[day] = days_count[day] + 1
end
puts days_count
end
If I copy and paste the above in irb, then:
> count_days(%w[SU MO])
{"SU"=>1, "MO"=>1}
> count_days(%w[SU SU MO])
{"SU"=>2, "MO"=>1}
Basically, consistent with prior answers. But, I thought an additional example couldn't hurt.

Word Count with Ruby

I am trying to figure out a way to count a words in a particular string that contains html.
Example String:
<p>Hello World</p>
Is there a way in Ruby to count the words in between the p tags? Or any tag for that matter?
Examples:
<p>Hello World</p>
<h2>Hello World</h2>
<li>Hello World</li>
Thanks in advance!
Edit (here is my working code)
Controller:
class DashboardController < ApplicationController
def index
#pages = Page.find(:all)
#word_count = []
end
end
View:
<% #pages.each do |page| %>
<% page.current_state.elements.each do |el| %>
<% #count = Hpricot(el.description).inner_text.split.uniq.size %>
<% #word_count << #count %>
<% end %>
<li><strong>Page Name: <%= page.slug %> (Word Count: <%= #word_count.inject(0){|sum,n| sum+n } %>)</strong></li>
<% end %>
Here's how you can do it:
require 'hpricot'
content = "<p>Hello World...."
doc = Hpricot(content)
doc.inner_text.split.uniq
Will give you:
[
[0] "Hello",
[1] "World"
]
(sidenote: the output is formatted with awesome_print that I warmly recommend)
Sure
Use Nokogiri to parse the HTML/XML and XPath to find the element and its text value.
Split on whitespace to count the words
You'll want to use something like Hpricot to remove the HTML, then it's just a case of counting words in plain text.
Here is an example of stripping the HTML: http://underpantsgnome.com/2007/01/20/hpricot-scrub/
First start with something able to parse HTML like Hpricot, then use simple regular expression to do what you want (you can merely split over spaces and then count for example)

Resources